【拒绝算法PUA】LeetCode 2255. 统计是给定字符串前缀的字符串数目
目录
系列文章目录
专题总结:
C++刷题技巧总结:
题目 2116. 判断一个括号字符串是否有效
难度
描述
解题方法1
系列文章目录
专题总结:
- 【拒绝算法PUA】0x00-位运算
- 【拒绝算法PUA】0x01- 区间比较技巧
- 【拒绝算法PUA】0x02- 区间合并技巧
- 【拒绝算法PUA】0x03 - LeetCode 排序类型刷题
- 【拒绝算法PUA】LeetCode每日一题系列刷题汇总-2025年持续刷新中
C++刷题技巧总结:
- 温习C/C++]0x04 刷题基础编码技巧
题目 LeetCode 2255. 统计是给定字符串前缀的字符串数目
2255. 统计是给定字符串前缀的字符串数目https://leetcode.cn/problems/count-prefixes-of-a-given-string/description
难度
简单
描述
给你一个字符串数组 words
和一个字符串 s
,其中 words[i]
和 s
只包含 小写英文字母 。
请你返回 words
中是字符串 s
前缀 的 字符串数目 。
一个字符串的 前缀 是出现在字符串开头的子字符串。子字符串 是一个字符串中的连续一段字符序列。
示例 1:
输入:words = ["a","b","c","ab","bc","abc"], s = "abc" 输出:3 解释: words 中是 s = "abc" 前缀的字符串为: "a" ,"ab" 和 "abc" 。 所以 words 中是字符串 s 前缀的字符串数目为 3 。
示例 2:
输入:words = ["a","a"], s = "aa" 输出:2 解释: 两个字符串都是 s 的前缀。 注意,相同的字符串可能在 words 中出现多次,它们应该被计数多次。
提示:
1 <= words.length <= 1000
1 <= words[i].length, s.length <= 10
words[i]
和s
只 包含小写英文字母。
解题方法1
单向滑动窗口,获取s子字符串前缀,然后将前缀在words中查找和计数。
#include <iostream>
#include <vector>
#include <string>
#include <algorithm>
using namespace std;
class Solution {
public:
int countPrefixes(vector<string>& words, string s) {
int res = 0;
int left = 0;
int right = 0;
int len = s.size();
while (right <= len) {
string tmp = s.substr(left, right++);
if (std::count(words.begin(), words.end(), tmp) != 0) {
res += std::count(words.begin(), words.end(), tmp);
}
}
return res;
}
};
int main(int argc, char **argv) {
Solution obj;
vector<string> words = {"a","b","c","ab","bc","abc"};
string s = "abc";
// vector<string> words = {"a","a"};
// string s = "aa";
int ret = obj.countPrefixes(words, s);
cout << ret << endl;
return 0;
}
输出:
3
关注我,跟我一起每日一题!
【拒绝算法PUA】LeetCode每日一题系列刷题汇总-2025年持续刷新中