怎么找一家公司的网站,学技术包分配的培训机构,手表网站登录页背景图,青岛品牌网站建设求空格分割的英文句子中,最大单词长度。例如:“this is a word”,最大单词长度为4。要求:不能用 split 函数对字符串进行切分,算法复杂度为o(n)
public class MaxWordLength { public static int maxWordLength(String sentence) { if (se…
求空格分割的英文句子中,最大单词长度。例如:“this is a word”,最大单词长度为4。要求:不能用 split 函数对字符串进行切分,算法复杂度为o(n)
publicclassMaxWordLength{publicstaticintmaxWordLength(String sentence){if(sentence ==null|| sentence.isEmpty()){return0;}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;}publicstaticvoidmain(String[] args){String sentence ="this is a word";int maxLen =maxWordLength(sentence);System.out.println("Max word length: "+ maxLen);}}