求空格分割的英文句子中,最大单词长度。例如:“this is a word”,最大单词长度为4。要求:不能用 split 函数对字符串进行切分,算法复杂度为o(n)
public class MaxWordLength {
public static int maxWordLength(String sentence) {
if (sentence == null || sentence.isEmpty()) {
return 0;
}
int maxLength = 0;
int currentLength = 0;
for (int i = 0; i < sentence.length(); i++) {
char c = sentence.charAt(i);
if (c == ' ') {
if (currentLength > maxLength) {
maxLength = currentLength;
}
currentLength = 0;
} else {
currentLength++;
}
return maxLength;
}
public static void main(String[] args) {
String sentence = "this is a word";
int maxLen = maxWordLength(sentence);
System.out.println("Max word length: " + maxLen);
}
}