leetcode_434

Number of Segments in a String


Problem

数一个字符串中的单词数,用空格间隔

Solution

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
public class {
public int countSegments(String s) {
int count = 0;
int head = 0;
while(head<s.length() && s.charAt(head) == ' ') {
head++;
}
while( head<s.length() ) {
if(s.charAt(head) != ' '){
count++;
}
// 走完这一串字
while(head<s.length() && s.charAt(head) != ' '){
head++;
}
// 走完空格
while(head<s.length() && s.charAt(head) == ' '){
head++;
}
}
return count;
}
}