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

求空格分割的英文句子中,最大单词长度。例如:"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);  
    }  
}
相关推荐
a_j589 分钟前
算法与数据结构(环形链表)
数据结构·链表
粉032132 分钟前
Keeppalived 实现Nginx 的高可用集群
java·服务器·nginx
路在脚下@1 小时前
Java使用Redisson实现布隆过滤器
java·spring boot
东方芷兰1 小时前
算法笔记 04 —— 算法初步(下)
c++·笔记·算法
JNU freshman1 小时前
图论 之 迪斯科特拉算法求解最短路径
算法·图论
魔道不误砍柴功1 小时前
Java中的Stream API:从入门到实战
java·windows·python
晚安7201 小时前
idea添加web工程
java·前端·intellij-idea
xinghuitunan1 小时前
时间转换(acwing)c/c++/java/python
java·c语言·c++·python
青松@FasterAI1 小时前
【NLP算法面经】本科双非,头条+腾讯 NLP 详细面经(★附面题整理★)
人工智能·算法·自然语言处理
八月五1 小时前
Java并发编程——ThreadLocal
java·并发编程