LeetCode 5543 两个相同字符之间的最长子字符串

题目描述;

题目描述


各变量的作用;

count::记录正在查找的子字符串中与那两个相同字符(假设有)不相同的字符个数,初值为 0。

count1:记录子字符串中与那两个相同字符相同的字符个数,初值为 -1。
PS:后面提交中发现,子字符串中可以包含与那两个相同字符相同的字符。

flag:记录有没有两个相同的字符。

max:查找到的最大字符串长度。

代码:

class Solution {
    
    
    public int maxLengthBetweenEqualCharacters(String s) {
    
    
        char[] ch = s.toCharArray();
        int count = 0;
        int count1 = -1;
        int max = 0;
        boolean flag = false;
        for(int i = 0;i < ch.length;i++){
    
    
            count = 0;
            count1 = -1;
            for(int j = i + 1;j < ch.length;j++){
    
    
                if(ch[i] != ch[j]){
    
    
                    count++;
                }else{
    
    
                    flag = true;
                    count1++;
                    if(count + count1 > max){
    
    
                        max = count + count1;
                    }
                }
            }
        }
        if(flag){
    
    
            return max;
        }
        return -1;

    }
}

结果:

结果


猜你喜欢

转载自blog.csdn.net/weixin_43752257/article/details/109143363
今日推荐