求空格分割的英文句子中,最大单词长度。例如:"this is a word",最大单词长度为4。要求:不能用 split 函数对字符串进行切分,算法复杂度为o(n)
java
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);
}
}