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

求空格分割的英文句子中,最大单词长度。例如:"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);  
    }  
}
相关推荐
李庆政370几秒前
Reactor-core 响应式编程 spring-boot-starter-webflux
java·spring boot·reactor·响应式编程·reactor-core
是Smoky呢2 分钟前
springAI+向量数据库+RAG入门案例
java·开发语言·ai编程
huabiangaozhi12 分钟前
修改表字段属性,SQL总结
java·数据库·sql
请为小H留灯14 分钟前
一键解决 IDEA 中 Java 项目变橙色的问题!!!
java·ide·maven·intellij-idea·java项目
小文大数据33 分钟前
python实现HTML转PDF
java·前端·数据库
羊小蜜.33 分钟前
Mysql 03: 连接查询全解——内连接、外连接与复合条件查询
数据库·mysql·算法·连接查询
架构师沉默38 分钟前
为什么 Dubbo 从 ZooKeeper 转向 Nacos?
java·后端·架构
vivo互联网技术41 分钟前
CVPR 2026 | C²FG:用分数差异分析提高条件生成中CFG的引导
人工智能·算法·aigc
用户83071968408243 分钟前
Spring Prototype Bean的四种正确使用方式
java·spring boot·后端
永恒_顺其自然1 小时前
Java Web 传统项目异步分块上传系统实现方案
java·开发语言·前端