面试常见算法与解答

1、最长不含重复字符的子字符串
思路:滑动窗口+检测到重复的进行重新切割

  //情况只考虑小写
    static int findLongestCharsNotRepeated(String s) {
        int length = s.length();
        int a[] = new int[26];
        int cutLength = 0;
        int maxLeng = 0;
        for (int i = 0; i < 26; i++) {
            a[i] = -1;
        }
        for (int i = 0; i < length; i++) {
            int k = s.charAt(i) - 'a';
            int prePosition = a[k];
            //以前没有,直接加一
            if (prePosition < 0) {
                cutLength++;
            }
            //以前如果有,看是否在当前滑动窗口之中
            else {
                int c = i - prePosition;
                //如果在滑动窗口之中
                if (c <=cutLength) {
                    cutLength = c;
                }
                //不在滑动窗口之中
                else {
                    cutLength++;
                }
            }
            if (cutLength > maxLeng) {
                maxLeng = cutLength;
            }
            a[k] = i;
        }
        System.out.println(maxLeng);
        return cutLength;
    }

你可能感兴趣的:(面试常见算法与解答)