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

求空格分割的英文句子中,最大单词长度。例如:"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);  
    }  
}
相关推荐
想做小南娘,发现自己是女生喵18 分钟前
第 2 章 顺序表和 vector
java·数据结构·算法
艾醒1 小时前
2026年第29周(7.13-7.19)AI全复盘:技术突破、行业趣闻翻车、算力服务器商业动态
人工智能·算法
CHANG_THE_WORLD1 小时前
6.多线程的TCP通信
java·网络·tcp/ip
雪碧聊技术1 小时前
动态规划算法—01背包问题
算法·动态规划
bu_shuo1 小时前
c与cpp中的argc和argv
c语言·c++·算法
普贤莲花2 小时前
【2026年第29周---写于20260718】---整理,断舍离
程序人生·算法·生活
Reart2 小时前
Leetcode 674.最长连续递增序列 (719)
后端·算法
sun03222 小时前
【笔记】Spring MVC 相关介绍
java·spring·mvc
Reart2 小时前
Leetcode 300.最长递增子序列(719)
算法
可编程芯片开发2 小时前
VSG虚拟同步发电机simulink建模与仿真
算法