当前位置 : 主页 > 编程语言 > java >

[leetcode] 434. Number of Segments in a String

来源:互联网 收集:自由互联 发布时间:2022-08-15
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


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 字符串中的分段数量​​


上一篇:[leetcode] 1337. The K Weakest Rows in a Matrix
下一篇:没有了
网友评论