DEV Community

Wenqi Jiang
Wenqi Jiang

Posted on

Multi Search LCCI

Given a string band an array of smaller strings T, design a method to search b for each small string in T. Output positions of all strings in smalls that appear in big, where positions[i] is all positions of smalls[i].

Input: 
big = "mississippi"
smalls = ["is","ppi","hi","sis","i","ssippi"]
Output:  [[1,4],[8],[],[3],[1,4,7,10],[5]]
Enter fullscreen mode Exit fullscreen mode
  • 0 <= len(big) <= 1000
  • 0 <= len(smalls[i]) <= 1000
  • The total number of characters in smalls will not exceed 100000.
  • No duplicated strings in smalls.
  • All characters are lowercase letters.

https://leetcode.cn/problems/multi-search-lcci/

const int N = 100000 + 10;

class Solution {
private:
  int son[N][26], values[N], idx;
  vector<vector<int>> res;
  void insert(string &word, int val) {
    int p = 0;
    for (char &c : word) {
      int i = c - 'a';
      if (!son[p][i])
        son[p][i] = ++idx;
      p = son[p][i];
    }
    values[p] = val;
  }

  void search(int start, string &big) {
    int p = 0;
    for (int i = start; i < big.size(); i++) {
      int k = big[i] - 'a';
      if (!son[p][k])
        return;
      p = son[p][k];
      if (values[p] >= 0)
        res[values[p]].push_back(start);
    }
  }

public:
  vector<vector<int>> multiSearch(string big, vector<string> &smalls) {
    memset(son, 0, sizeof son);
    memset(values, -1, sizeof values);
    idx = 0;
    res.resize(smalls.size());

    for (int i = 0; i < smalls.size(); ++i)
      insert(smalls[i], i);

    for (int i = 0; i < big.size(); ++i)
      search(i, big);

    return res;
  }
};
Enter fullscreen mode Exit fullscreen mode

Top comments (0)