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

求空格分割的英文句子中,最大单词长度。例如:"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);  
    }  
}
相关推荐
wearegogog1231 小时前
基于 MATLAB 的卡尔曼滤波器实现,用于消除噪声并估算信号
前端·算法·matlab
韩师学子--小倪1 小时前
fastjson与gson的toString差异
java·json
一只小小汤圆1 小时前
几何算法库
算法
Drawing stars1 小时前
JAVA后端 前端 大模型应用 学习路线
java·前端·学习
Evand J1 小时前
【2026课题推荐】DOA定位——MUSIC算法进行多传感器协同目标定位。附MATLAB例程运行结果
开发语言·算法·matlab
nbsaas-boot1 小时前
SQL Server 存储过程开发规范(公司内部模板)
java·服务器·数据库
行百里er2 小时前
用 ThreadLocal + Deque 打造一个“线程专属的调用栈” —— Spring Insight 的上下文管理术
java·后端·架构
leo__5202 小时前
基于MATLAB的交互式多模型跟踪算法(IMM)实现
人工智能·算法·matlab
忆锦紫2 小时前
图像增强算法:Gamma映射算法及MATLAB实现
开发语言·算法·matlab
玄〤2 小时前
黑马点评中 VoucherOrderServiceImpl 实现类中的一人一单实现解析(单机部署)
java·数据库·redis·笔记·后端·mybatis·springboot