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思路:
这题审题审疯了,一开始当看成了有多少个单词,但是后来试了几次才发现,只要是用空格分开的就算是一段。
public class Solution {
public int countSegments(String s) {
if (s == null || s.length() == 0) {
return 0;
}
int count = 0;
for (int i = 0; i < s.length(); i++) {
if(s.charAt(i) != ' '){
if (i == 0) {
count++;
} else if (i > 0 && s.charAt(i - 1) == ' ') {
count++;
}
}
}
return count;
}
}