题源:字符串最后一个单词的长度
题目描述
计算字符串最后一个单词的长度,单词以空格隔开,字符串长度小于5000。(注:字符串末尾不以空格为结尾)
输入描述:
输入一行,代表要计算的字符串,非空,长度小于5000。
输出描述:
输出一个整数,表示输入字符串最后一个单词的长度。
示例1
输入:
hello nowcoder
输出:
8
说明:
最后一个单词为nowcoder,长度为8
算法思路:直接遍历整个字符串,如果遇到空格了,那就重新计算cnt,没有遇到的话,cnt++,最后返回cnt即可。
题解(cpp):
#include <iostream>
using namespace std;
int main() {
int count = 0;
string s;
getline(cin, s);
int i=s.length()-1;
//如果还在字符内,并且非空格,那就加一
//是空格则全部重新计算
while(i>=0 && s[i]!=' '){
i--;
count++;
}
cout<<count;
}
来都来了,再做一题力扣的
题目:2185. 统计包含给定前缀的字符串
给你一个字符串数组 words 和一个字符串 pref 。
返回 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" 作为前缀的字符串。
算法思路:遍历字符串s,用find进行对比,如果前缀相同,则ans++,否则不相加,最后返回答案即可。
题解:
class Solution {
public:
int prefixCount(vector<string>& words, string pref) {
int ans = 0;
//find(pref) == 0代表以pref开始
for (string& s : words)
ans += !s.find(pref);
return ans;
}
};