434. Number of Segments in a String
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
class Solution {
public int countSegments(String s) {
int count = 0;
for (int i = 0; i < s.length(); i++) {
if (s.charAt(i) != ' ' && (i == 0 || s.charAt(i - 1) == ' ')
count++;
}
return count;
}
}
本文介绍了一种用于计算字符串中非空格字符连续段数量的算法。通过遍历字符串并检查每个字符是否为空格,该算法能准确地统计出字符串包含的单词数量。
464

被折叠的 条评论
为什么被折叠?



