No.48-最长不包含重复字符的子字符串(Java版)

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/u012292754/article/details/89382935

1 最长不包含重复字符的子字符串

在这里插入图片描述

 public static int longestSubstring(String str) {
        if (str == null) {
            return 0;
        }

        int maxLen = 0;
        int curLen = 0;
        int[] positions = new int[26];

        for (int i = 0; i < 26; i++) {
            positions[i] = -1; // -1表示没有出现过
        }

        for (int i = 0; i < str.length(); i++) {
            int curChar = str.charAt(i) - 'a';
            int prePosition = positions[curChar];

            // 当前字符与它上次出现位置之间的距离
            int distance = i - prePosition;

            // 当前字符第一次出现,或者前一个非重复子字符串中没有包含当前字符
            if (prePosition < 0 || distance > curLen) {
                curLen++;
            } else {
                // 更新最长非重复子字符串的长度
                if (curLen > maxLen) {
                    maxLen = curLen;
                }

                curLen = distance;
            }

            positions[curChar] = i; // 更新字符出现的位置

        }


        if (curLen > maxLen) {
            maxLen = curLen;
        }

        return maxLen;
    }

    public static void main(String[] args) {

        String s = "acabcacfr";
        int res = longestSubstring(s);
        System.out.println(res);
    }

猜你喜欢

转载自blog.csdn.net/u012292754/article/details/89382935