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

求空格分割的英文句子中,最大单词长度。例如:"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);  
    }  
}
相关推荐
virus59451 小时前
悟空CRM mybatis-3.5.3-mapper.dtd错误解决方案
java·开发语言·mybatis
一匹电信狗1 小时前
【LeetCode_547_990】并查集的应用——省份数量 + 等式方程的可满足性
c++·算法·leetcode·职场和发展·stl
鱼跃鹰飞2 小时前
Leetcode会员尊享100题:270.最接近的二叉树值
数据结构·算法·leetcode
Queenie_Charlie2 小时前
小陶的疑惑2
数据结构·c++·树状数组
没差c2 小时前
springboot集成flyway
java·spring boot·后端
时艰.2 小时前
Java 并发编程之 CAS 与 Atomic 原子操作类
java·开发语言
梵刹古音3 小时前
【C语言】 函数基础与定义
c语言·开发语言·算法
编程彩机3 小时前
互联网大厂Java面试:从Java SE到大数据场景的技术深度解析
java·大数据·spring boot·面试·spark·java se·互联网大厂
笨蛋不要掉眼泪3 小时前
Spring Boot集成LangChain4j:与大模型对话的极速入门
java·人工智能·后端·spring·langchain
筵陌3 小时前
算法:模拟
算法