792. 匹配子序列的单词数
中等
282
相关企业
给定字符串 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 都只由小写字母组成。
通过次数
23.7K
提交次数
47.5K
通过率
49.9%
题解:比较两个字符串s和t,其中一个是另外一个子串的问题,可以使用双指针一次遍历。那么这道题目就是在外面再加一层for循环,遍历完所有的字符串数组就可以了。于是我就提交了,发现超时了。。。。既然超时了,那么就要算法优化,删除一些重复的操作。看着超时的测试用例,我忽然就懂了,因为测试的字符串有很多是重复的,所以增加了一个哈希表来去重,这样再遍历一遍哈希表,就可以通过了。具体看代码,使用table[26]是用来提前结束不匹配的情况的优化。
class Solution {
public:
int numMatchingSubseq(string s, vector<string>& words) {
int sum=0;
int table[26]={0};
unordered_map<string,int> Hashmap;
for(auto ch:s)
{
table[ch-'a']++;
}
for(auto str:words)
{
Hashmap[str]++;
}
for(auto p:Hashmap)
{
string temStr=p.first;
int k=0;
int sk=0;
// 计算是否存在
bool flag=true;
int temptable[26]={0};
for(auto i:temStr)
{
temptable[i-'a']++;
if(temptable[i-'a']>table[i-'a'])
{
flag=false;
break;
}
}
if(flag)
{
while(k<temStr.size() && sk<s.size())
{
if(temStr[k]==s[sk])
{
k++;
sk++;
}
else
{
sk++;
}
}
if(k>temStr.size()-1)
{
sum+=p.second;
}
}
}
return sum;
}
};
时间168 ms
击败
63.30%
内存42.1 MB
击败
74.64%