1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46
| class Solution { Set<Character> set = new HashSet<>(); Set<String> set2 = new HashSet<>(); public int numMatchingSubseq(String S, String[] words) { int ans = 0;
for (int i = 0; i < S.length(); i++) { set.add(S.charAt(i)); }
for (String word: words) { if (set2.contains(word) || compare(S, word)) { set2.add(word); ans++; } } return ans; }
public boolean compare(String S, String word){ int k = 0; int i = 0;
for (i = 0; i < word.length(); i++) { if (!set.contains(word.charAt(i))) { return false; }
while (k < S.length() && S.charAt(k) != word.charAt(i)){ k++; }
if (k >= S.length() || S.charAt(k) != word.charAt(i)) { return false; }
k++; }
return true; } }
|