题目
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
题意
给定一个字符串,计算片段的数量。一个片段定义为连续的没有空格的字母序列。
分析及解答
解答1:(击败 %78)
public static int countSegments(String s) {
char[] array = s.toCharArray();
int len = array.length;
boolean isPreSpace = true;
boolean isCurrentSpace = true;
int count= 0;
for(int i = 0; i <len ;i++){
isCurrentSpace = (array[i] == ' ');
if(isPreSpace){
if(isCurrentSpace){
isPreSpace = true;
}else{
isPreSpace = false;
count++;
}
}else{
isPreSpace = isCurrentSpace;
}
}
return count;
}
解答2:(击败 3%)(反面教材)
- 利用了正则表达式。(较为消耗时间)
public int countSegments(String s) {
if(s.equals("")) return 0;
String[] results = s.split("\\s+");
if(results == null || results.length == 0) return 0;
if(results[0].equals("")){
return results.length -1;
}
return results.length;
}