You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
create a trie for smalls. Iterate through all substring of big. If the substring is found in the trie, save the ID of the trieNode. ID is the corresponding position of each small in the smalls array.
Complexity:
Time: O(N^2) N is the length of big
Space: O(k* n) n is the avg length of small words, k is the size of character set
classSolution{TrieNoderoot=newTrieNode();publicint[][]multiSearch(Stringbig,String[]smalls){intm=smalls.length;for(inti=0;i<m;i++){insert(smalls[i],i);}//use an array of arraylist to store results List<Integer>[] res = new List[m];
for(int i=0;i<m;i++){res[i]=newArrayList<Integer>();}//iterate over all substring of big, if the substring is in the trie, save the indexintn=big.length();for(inti=0;i<n;i++){TrieNodecurr=root;for(intj=i;j<n;j++){charc=big.charAt(j);if(curr.children[c-'a']==null)break;curr=curr.children[c-'a'];if(curr.isWord==true){res[curr.ID].add(i);}}}//convert res to 2d arrayint[][]ret=newint[m][];for(inti=0;i<m;i++){ret[i]=newint[res[i].size()];for(intj=0;j<res[i].size();j++){ret[i][j]=res[i].get(j);}}returnret;}//insert new word into trieprivatevoidinsert(Stringword,intindex){TrieNodecurr=root;for(inti=0;i<word.length();i++){charc=word.charAt(i);if(curr.children[c-'a']==null){curr.children[c-'a']=newTrieNode();}curr=curr.children[c-'a'];}curr.ID=index;curr.isWord=true;}privateclassTrieNode{TrieNode[]children;intID;//store the index of smallsbooleanisWord;publicTrieNode(){children=newTrieNode[26];isWord=false;ID=-1;}}}
https://leetcode-cn.com/problems/multi-search-lcci/
注意如何create trie, insert, search only use a global trienode
注意字符串字串内层循环j从i开始
Idea:
create a trie for smalls. Iterate through all substring of big. If the substring is found in the trie, save the ID of the trieNode. ID is the corresponding position of each small in the smalls array.
Complexity:
Time: O(N^2) N is the length of big
Space: O(k* n) n is the avg length of small words, k is the size of character set
Originally posted by @panda-qin in leetcode-pp/91alg-5-daily-check#94 (comment)
The text was updated successfully, but these errors were encountered: