leetcode 792. Number of Matching Subsequences
2024-09-30 00:34:03
Given string S and a dictionary of words words, find the number of words[i] that is a subsequence of S.
Example :
Input:
S = "abcde"
words = ["a", "bb", "acd", "ace"]
Output: 3
Explanation: There are three words in words that are a subsequence of S: "a", "acd", "ace".
Note:
All words in words and S will only consists of lowercase letters.
The length of S will be in the range of [1, 50000].
The length of words will be in the range of [1, 5000].
The length of words[i] will be in the range of [1, 50].
思路:先用vector记录每个字母出现的位置,然后遍历每个单词,如果每个字母的位置是递增的那么这个单词就符合要求。如何判断位置见的递增关系呢?可以用二分实现。具体看代码
class Solution {
public:
int numMatchingSubseq(string S, vector<string>& words) {
vector<int> v[26];
for (int i = 0; i < S.size(); ++i) {
v[S[i]-'a'].emplace_back(i);
}
int ans = 0;
for (auto i : words) {
int mark = 0;
int y = -1;
for(auto c : i) {
int x = c - 'a';
if (v[x].empty()) {
mark = 1; break;
}
int pos = upper_bound(v[x].begin(), v[x].end(), y) - v[x].begin();
if (pos < v[x].size()) {
y = v[x][pos];
} else {
mark = 1; break;
}
}
if (!mark) ans++;
}
return ans;
}
};
最新文章
- DevExpress学习系列(控件篇):GridControl的基本应用
- 初学python第二天
- C#调用c++Dll 结构体数组指针的问题
- js 格式化数字保留2位小数
- Android广播机制:Broadcast
- nginx笔记----安装
- 为 vsftpd 启动 vsftpd:500 OOPS: bad bool value in config file for: pasv_enable
- Deep Learning深入研究整理学习笔记五
- React Native与原生项目连接与发布
- Spring事务隔离级别
- <;script>;的用法
- LxmlLinkExtractor类参数解析
- C# BackJson Beautiful format
- 动态规划dp
- Mtlab:抛物型方程的交替方向隐格式(ADI)
- 剑指offer——从上往下打印二叉树
- Codeforces Round #449 (Div. 2)
- Java坦克大战(一)
- 【贪心】PAT 1033. To Fill or Not to Fill (25)
- MapReduce的计数器