【数字字符串互转】【C++】周赛#282 一题选手 LeetCode#74 6008./2185.统计包含给定前缀的字符串E
2月13日
2月19日
第一次一题选手-2.13
第二次二题选手-2.19
第三次一题选手-2.27
You are given an array of strings words and a string pref.
Return the number of strings in words that contain pref as a prefix.
A prefix of a string s is any leading contiguous substring of s.
Example 1:
Input: words = ["pay","attention","practice","attend"], pref = "at"
Output: 2
Explanation: The 2 strings that contain "at" as a prefix are: "attention" and "attend".
Example 2:
Input: words = ["leetcode","win","loops","success"], pref = "code"
Output: 0
Explanation: There are no strings that contain "code" as a prefix.
Constraints:
-
1 <= words.length <= 100 -
1 <= words[i].length, pref.length <= 100 -
words[i] and pref consist of lowercase English letters.
返回 words 中以 pref 作为 前缀 的字符串的数目。
字符串 s 的 前缀 就是 s 的任一前导连续字符串。
示例 1:
输入:words = ["pay","attention","practice","attend"], pref = "at"
输出:2
解释:以 "at" 作为前缀的字符串有两个,分别是:"attention" 和 "attend" 。
示例 2:
输入:words = ["leetcode","win","loops","success"], pref = "code"
输出:0
解释:不存在以 "code" 作为前缀的字符串。
提示:
-
1 <= words.length <= 100 -
1 <= words[i].length, pref.length <= 100 -
words[i] 和 pref 由小写英文字母组成
「题解」
昨天刚做过537. 复数乘法,两题都用到了substr()
遍历字符串数组,找到字符串前缀有pref的就count加1,返回结果
「substr()」
返回一个string,它是原始string的一部分或全部的拷贝。可以传递给substr一个可选的开始位置和计数值:
string s("hello world");
string s2 = s.substr(0, 5); // s2 = hello
string s3 = s.substr(6); // s3 = world
string s4 = s.substr(6, 11);// s3 = world
string s5 = s.substr(12); // 抛出一个out_of_range异常
如果开始位置超过string大小,则substr()抛出out_of_range异常。如果开始位置加上计数值大于string的大小,则substr()会调整计数值,只拷贝到string的末尾
s.substr(pos, n) - 返回一个string,包含s中从pos开始的n个字符的拷贝。pos的默认值为0。n的默认值为s.size() - pos,即拷贝从pos开始的所有字符
「AC代码」
class Solution {
public:
int prefixCount(vector<string>& words, string pref)
{
int count = 0;
for (int i = 0; i < words.size(); ++i)
{
if (words[i].substr(0, pref.size()) == pref)
count++;
}
return count;
}
};
// 一次通过