题目
给定字符串 s 和字符串数组 words, 返回 words[i] 中是s的子序列的单词个数 。
字符串的 子序列 是从原始字符串中生成的新字符串,可以从中删去一些字符(可以是none),而不改变其余字符的相对顺序。
例如, “ace” 是 “abcde” 的子序列。
示例
输入: s = “abcde”, words = [“a”,“bb”,“acd”,“ace”]
输出: 3
解释: 有三个是 s 的子序列的单词: “a”, “acd”, “ace”。
输入: s = “dsahjpjauf”, words = [“ahjpjau”,“ja”,“ahbwzgqnuk”,“tnmlanowax”]
输出: 2
来源:力扣(LeetCode)
链接:https://leetcode.cn/problems/number-of-matching-subsequences
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。
方法1:预处理+二分查找
⭐题解:https://leetcode.cn/problems/number-of-matching-subsequences/solution/-by-muse-77-1vhl/
Java实现
class Solution {
public int numMatchingSubseq(String s, String[] words) {
List<Integer>[] sm = new ArrayList[26];
char[] sc = s.toCharArray();
for (int i = 0; i < sc.length; i++) {
if (sm[sc[i] - 'a'] == null) sm[sc[i] - 'a'] = new ArrayList<>();
sm[sc[i] - 'a'].add(i);
}
int res = words.length;
for (String word : words) {
int compareIndex = -1, index;
for (int i = 0; i < word.length(); i++) {
if (sm[word.charAt(i) - 'a'] == null ||
((index = findCharIndex(compareIndex, sm[word.charAt(i) - 'a'])) <= compareIndex)) {
res--;
break;
}
compareIndex = index;
}
}
return res;
}
public int findCharIndex(int compareIndex, List<Integer> list) {
int l = 0, r = list.size() - 1, mid;
while (l < r) {
mid = l + r >> 1;
if (list.get(mid) > compareIndex) r = mid;
else l = mid + 1;
}
return list.get(l);
}
}