前言:为了后续的实习面试,开始疯狂刷题,非常欢迎志同道合的朋友一起交流。因为时间比较紧张,目前的规划是先过一遍,写出能想到的最优算法,第二遍再考虑最优或者较优的方法。如有错误欢迎指正。博主首发优快云,mcf171专栏。
博客链接:mcf171的博客
——————————————————————————————
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关于java源生的String.split方法有一些不太好用的地方,好像Apache得StringUtils比较好用,但是做题应该不能用这个,只能用老办法,再遍历一遍数组,从时间复杂度上来说其实无所谓。但是略不爽、 Your runtime beats 12.35% of java submissions.
public class Solution {
public int countSegments(String s) {
if(s.length() == 0) return 0;
int result = 0;
boolean flag = false;
char[] chs = s.toCharArray();
String[] strs = s.split(" ");
for(String str : strs){
if(str.length() != 0) result ++;
}
return result;
}
}