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

求空格分割的英文句子中,最大单词长度。例如:"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);  
    }  
}
相关推荐
用户094248568031 分钟前
第38章:从零构建JVM稳定性平台最小闭环
java·jvm
局部有解2 分钟前
Hot100 - 三数之和
数据结构·c++·算法
辉艺棉麻小张3 分钟前
用 JSON 建模面料规格:成分、克重、支数与公定回潮率字段设计
数据结构
longlongzihan19 分钟前
C++ 常用数据结构速查:vector、stack、queue、list、树、图、哈希表等声明与核心操作
数据结构·c++·list
silvamux_27 分钟前
Spring Boot 调用大模型 api 最小可跑教程
java·spring boot·后端
今年下半年29 分钟前
【Spring Boot 】通过 OpenFeign 请求第三方接口
java·spring boot·后端·openfeign
思茂信息31 分钟前
CST技术案例:加载正弦曲线的平面螺旋天线仿真研究
算法·平面·emc·cst·电磁仿真·仿真辐射
嫂子开门我是_我哥34 分钟前
敏感性分析
算法·机器学习·论文笔记
三翼鸟数字化技术团队34 分钟前
Springboot + WebFlux + Disruptor 实现数据转发
java·spring boot
别动我齐刘海38 分钟前
实时控制学习2
linux·c++·人工智能·学习·算法