美文网首页
[算法] - 字符串 - 判断出现字符串最长长度

[算法] - 字符串 - 判断出现字符串最长长度

作者: 夹胡碰 | 来源:发表于2021-03-12 14:01 被阅读0次

    描述

    一个含有多个空格的ASCII串,求最长非空格字符串的长度,尽可能最优。例如,输入:"aa bc aaaa aaa",输出:4;

    代码

    public static void main(String[] args) {
        String s = "   ";
        int maxLength = getMaxLength(s);
        System.out.println(maxLength);
    }
    
    // 时间复杂度 O(n),空间复杂度 O(1)
    public static int getMaxLength(String s){
        int maxLen = 0;
        int curLen = 0;
        for(char chars : s.toCharArray()){
            if(chars != ' '){
                curLen ++;
            }
    
            if(chars == ' '){
                if(curLen > maxLen){
                    maxLen = curLen;
                }
                curLen = 0;
            }
        }
    
        return curLen > maxLen ? curLen : maxLen;
    }
    

    相关文章

      网友评论

          本文标题:[算法] - 字符串 - 判断出现字符串最长长度

          本文链接:https://www.haomeiwen.com/subject/mjlzqltx.html