笔试题 求空格分割的英文句子中,最大单词长度。

求空格分割的英文句子中,最大单词长度。例如:"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);  
    }  
}
相关推荐
码出财富4 小时前
SpringBoot 内置的 20 个高效工具类
java·spring boot·spring cloud·java-ee
多米Domi0114 小时前
0x3f第33天复习 (16;45-18:00)
数据结构·python·算法·leetcode·链表
我是小疯子664 小时前
Python变量赋值陷阱:浅拷贝VS深拷贝
java·服务器·数据库
森叶4 小时前
Java 比 Python 高性能的原因:重点在高并发方面
java·开发语言·python
二哈喇子!4 小时前
Eclipse中导入外部jar包
java·eclipse·jar
微露清风4 小时前
系统性学习C++-第二十二讲-C++11
java·c++·学习
罗湖老棍子5 小时前
【例4-11】最短网络(agrinet)(信息学奥赛一本通- P1350)
算法·图论·kruskal·prim
方圆工作室5 小时前
【C语言图形学】用*号绘制完美圆的三种算法详解与实现【AI】
c语言·开发语言·算法
曹仙逸5 小时前
数据结构day04
数据结构
Lips6115 小时前
2026.1.16力扣刷题
数据结构·算法·leetcode