思路:
1.爆破法,对每个单词进行比对,但是超时
2,考虑只遍历S一次
class Solution {
public int numMatchingSubseq(String S, String[] words) {
HashMap<Character,ArrayList<String>> map = new HashMap<>();
for(int i = 0;i < words.length;i++){
char c = words[i].charAt(0);
if(map.containsKey(c)){
ArrayList<String> list = map.get(c);
list.add(words[i]);
}else{
ArrayList<String> list = new ArrayList();
list.add(words[i]);
map.put(c,list);
}
}
int count = 0;
for(int i = 0;i < S.length();i++){
char c = S.charAt(i);
if(map.containsKey(c)){
ArrayList<String> list = map.get(c);
map.remove(c);
for(String str:list){
if(str.length() == 1){
count++;
continue;
}
char b = str.charAt(1);
if(map.containsKey(b)){
ArrayList<String> list1 = map.get(b);
list1.add(str.substring(1,str.length()));
}else{
ArrayList<String> list1 = new ArrayList();
list1.add(str.substring(1,str.length()));
map.put(b,list1);
}
}
}
}
return count;
}
}
class Solution {
public int numMatchingSubseq(String S, String[] words) {
int ans = 0;
ArrayList<Node>[] heads = new ArrayList[26];
for (int i = 0; i < 26; ++i)
heads[i] = new ArrayList<Node>();
for (String word: words)
heads[word.charAt(0) - 'a'].add(new Node(word, 0));
for (char c: S.toCharArray()) {
ArrayList<Node> old_bucket = heads[c - 'a'];
heads[c - 'a'] = new ArrayList<Node>();
for (Node node: old_bucket) {
node.index++;
if (node.index == node.word.length()) {
ans++;
} else {
heads[node.word.charAt(node.index) - 'a'].add(node);
}
}
old_bucket.clear();
}
return ans;
}
}
class Node {
String word;
int index;
public Node(String w, int i) {
word = w;
index = i;
}
}
作者:LeetCode
链接:https://leetcode-cn.com/problems/number-of-matching-subsequences/solution/pi-pei-zi-xu-lie-de-dan-ci-shu-by-leetcode/
来源:力扣(LeetCode)
著作权归作者所有。商业转载请联系作者获得授权,非商业转载请注明出处。