题目描述
给定字符串 S 和单词字典 words, 求 words[i] 中是 S 的子序列的单词个数。
示例:
输入:
S = “abcde”
words = [“a”, “bb”, “acd”, “ace”]
输出: 3
解释: 有三个是 S 的子序列的单词: “a”, “acd”, “ace”。
注意:
所有在words和 S 里的单词都只由小写字母组成。
S 的长度在 [1, 50000]。
words 的长度在 [1, 5000]。
words[i]的长度在[1, 50]。
题解
使用HashMap对words中重复的字符串进行过滤。
package dongtaiguihua;
import java.util.HashMap;
public class DT_792 {
public static void main(String[] args) {
DT_792 dt = new DT_792();
String s = "abcde";
String[] words = {"a", "bb", "acd", "ace"};
int sum = dt.numMatchingSubseq(s,words);
System.out.println(sum);
}
public int numMatchingSubseq(String S, String[] words) {
HashMap<String,Integer> map = new HashMap<>();
for(int i =0; i < words.length; i++) {
if(!map.containsKey(words[i])) {
map.put(words[i],1);
} else {
map.put(words[i],map.get(words[i]) + 1);
}
}
int sum = 0;
for(String s : map.keySet()) {
int index = isSubsequence(S,s);
if(index == 1) {
sum += map.get(s);
}
}
return sum;
}
public int isSubsequence(String s,String t) {
int i = 0;
int j = 0;
while(i < s.length() && j < t.length()) {
if(s.charAt(i) == t.charAt(j)) j++;
i ++;
}
if(j == t.length()) {
return 1;
} else {
return 0;
}
}
}