What is the count of segments in a given string using LeetCode problem 434?
- 内容介绍
- 文章标签
- 相关推荐
本文共计314个文字,预计阅读时间需要2分钟。
描述:计算字符串中连续非空格字符序列(称为段)的数量。请注意,该字符串不包含任何非打印字符。
示例:输入:Hello,my name
Description
Count the number of segments in a string, where a segment is defined to be a contiguous sequence of non-space characters.
Please note that the string does not contain any non-printable characters.
Example:
Input:
"Hello, my name is John"Output:
5分析
题目的意思是:统计出一个字符串里面的单词。
- 这道题是easy类型的题目,但是不仔细处理空格的话,就可能AC不全。
- 思路很简单,从头到尾的遍历,遇见空格之后又遇到字符,说明前面已经遍历了一个单词,就进行+1操作。最后将统计结果返回就行了。
代码
class Solution {public:
int countSegments(string s) {
int cnt=0;
int n=s.length();
for(int i=0;i<s.length();i++){
if(s[i]==' ') continue;
cnt++;
while(i<n&&s[i]!=' ') i++;
}
return cnt;
}
};
参考文献
[LeetCode] Number of Segments in a String 字符串中的分段数量
本文共计314个文字,预计阅读时间需要2分钟。
描述:计算字符串中连续非空格字符序列(称为段)的数量。请注意,该字符串不包含任何非打印字符。
示例:输入:Hello,my name
Description
Count the number of segments in a string, where a segment is defined to be a contiguous sequence of non-space characters.
Please note that the string does not contain any non-printable characters.
Example:
Input:
"Hello, my name is John"Output:
5分析
题目的意思是:统计出一个字符串里面的单词。
- 这道题是easy类型的题目,但是不仔细处理空格的话,就可能AC不全。
- 思路很简单,从头到尾的遍历,遇见空格之后又遇到字符,说明前面已经遍历了一个单词,就进行+1操作。最后将统计结果返回就行了。
代码
class Solution {public:
int countSegments(string s) {
int cnt=0;
int n=s.length();
for(int i=0;i<s.length();i++){
if(s[i]==' ') continue;
cnt++;
while(i<n&&s[i]!=' ') i++;
}
return cnt;
}
};
参考文献
[LeetCode] Number of Segments in a String 字符串中的分段数量

