给定字符串 s 和字符串数组 words, 返回 words[i] 中是s的子序列的单词个数 。
字符串的 子序列 是从原始字符串中生成的新字符串,可以从中删去一些字符(可以是none),而不改变其余字符的相对顺序。
例如, “ace” 是 “abcde” 的子序列。
示例 1:
输入: s = "abcde", words = ["a","bb","acd","ace"]
输出: 3
解释: 有三个是 s 的子序列的单词: "a", "acd", "ace"。
Example 2:
输入: s = "dsahjpjauf", words = ["ahjpjau","ja","ahbwzgqnuk","tnmlanowax"]
输出: 2
提示:
1 <= s.length <= 5 * 104
1 <= words.length <= 5000
1 <= words[i].length <= 50
words[i]和 s 都只由小写字母组成。
来源:力扣(LeetCode)
链接:https://leetcode.cn/problems/number-of-matching-subsequences
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。
find暴力:
class Solution { public: int numMatchingSubseq(string s, vector<string>& words) { int cnt = 0; for (string &word : words) { int cur = -1; bool ok = true; for (char &c : word) { // 查找 cur 之后是否出现了 c cur = s.find(c, cur + 1); if (cur == string::npos) { ok = false; break; } } if (ok) cnt++; } return cnt; } };
队列分桶:
class Solution { public: int numMatchingSubseq(string s, vector<string>& words) { vector<queue<string>> d(26); for (auto& w : words) d[w[0] - 'a'].emplace(w); int ans = 0; for (char& c : s) { auto& q = d[c - 'a']; for (int k = q.size(); k; --k) { auto t = q.front(); q.pop(); if (t.size() == 1) ++ans; else d[t[1] - 'a'].emplace(t.substr(1)); } } return ans; } };
二分哈希:
class Solution { public: int numMatchingSubseq(string s, vector<string>& words) { vector<vector<int>> d(26); for (int i = 0; i < s.size(); ++i) d[s[i] - 'a'].emplace_back(i); int ans = 0; auto check = [&](string& w) { int i = -1; for (char& c : w) { auto& t = d[c - 'a']; int j = upper_bound(t.begin(), t.end(), i) - t.begin(); if (j == t.size()) return false; i = t[j]; } return true; }; for (auto& w : words) ans += check(w); return ans; } };
标签:792,分桶,int,auto,cur,二分法,words,ans,string From: https://www.cnblogs.com/slowlydance2me/p/16898886.html