题目:
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.
思路与步骤:
基本思路:
依次读入字符串中的字符,遇到字符跳过,直到空格,此时count+1;
细节处理:
当出现连续空格时,所以遇到空格要循环读直到空格结束,此时才count+1;
若开始就有空格,所以要先判断遇见的空格,若不再出现字符,则返回0;若出现了字符,则此后count才开始计数。
学习别人的思路:
循环中直接判断是否是字符,如果是,并且其前一个是空格,则count计数。
此时要注意,当字符串中只有一个有效字符时,“前一个”会造成数组下标异常,所以多一条判断,但是不用再 if 了,直接 i==0 || s.charAt(i-1)==' '即可。这里要注意,不能写成s.charAt(i-1)=='
' || i==0 .程序后面会详细解释。
编程实现:
我的解法:
public class Solution {
public int countSegments(String s) {
int count = 0;
for(int i=0; i<s.length(); i++){
while(s.charAt(i) == ' ' && i<s.length()-1) i++;
if(s.charAt(i) != ' '){
while(s.charAt(i) != ' ' && i<s.length()-1) i++;
count++;
}
}
return count;
}
}
别人的程序:
public 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++;
//Notice: The following sentence - java.lang.StringIndexOutOfBoundsException: String index out of range: -1
//if(s.charAt(i)!=' ' && (s.charAt(i-1)==' ' || i==0)) count++; //Not AC
}
return count;
}
}
这里需要特别注意!