给定字符串 S 和单词字典 words, 求 words[i] 中是 S 的子序列的单词个数。
示例:
输入:
S = “abcde”
words = [“a”, “bb”, “acd”, “ace”]
输出: 3
解释: 有三个是 S 的子序列的单词: “a”, “acd”, “ace”。
class Solution {
public int numMatchingSubseq(String S, String[] words) {
int n=S.length(),res=0;
Set<String> set=new HashSet<>();
Set<String> set2=new HashSet<>();
for(String c:words)
{
if(set2.contains(c)) continue;
if(set.contains(c)) {
res++;
continue;
}
int m=c.length(),j=0;
boolean find=false;
for(int i=0;i<n;i++)
{
if(S.charAt(i)==c.charAt(j))
j++;
if(j==m) {
find=true;
res++;
break;
}
}
if(find) set.add(c);else set2.add(c);
}
return res;
}
}