描述
一个含有多个空格的ASCII串,求最长非空格字符串的长度,尽可能最优。例如,输入:"aa bc aaaa aaa",输出:4;
代码
public static void main(String[] args) {
String s = " ";
int maxLength = getMaxLength(s);
System.out.println(maxLength);
}
// 时间复杂度 O(n),空间复杂度 O(1)
public static int getMaxLength(String s){
int maxLen = 0;
int curLen = 0;
for(char chars : s.toCharArray()){
if(chars != ' '){
curLen ++;
}
if(chars == ' '){
if(curLen > maxLen){
maxLen = curLen;
}
curLen = 0;
}
}
return curLen > maxLen ? curLen : maxLen;
}
网友评论