题目:
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.
注意:
1、我开始的时候多虑了逗号的问题,后来发现英文里面逗号后面也是一个空格,所以不需要多考虑。
2、然后这个if这里我想了半天,最后终于明白了,他的意思是说,当前不是空格,前一个是空格,才++。还要加上当前不是空格,而且i==0的情况。因为4个空格是五个片段,而且这个还可以同时包含另一种情况:只有一个字符,比如“Hello”。
Code:
public int countSegments(String s) {
int res=0;
for(int i=0; i<s.length(); i++)
if(s.charAt(i)!=' ' && (i==0 || s.charAt(i-1)==' '))
res++;
return res;
}