力扣3. 无重复字符的最长子串

2021-12-09  本文已影响0人  阿丹_90

题目

来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/longest-substring-without-repeating-characters

答案

class Solution {
    public int lengthOfLongestSubstring(String s) {
        char[] chars = s.toCharArray();
        int max = 0;
        for (int i = 0; i < chars.length; i++) {
            int length = lengthOfLongestSubstring(chars, i, chars.length, max);
            if (max < length) max = length;
            if (chars.length - i <= max) return max;
        }
        return max;
    }

    private int lengthOfLongestSubstring(char[] chars, int startIndex, int endIndex, int max) {
        if (endIndex - startIndex <= max) return max;
        for (int i = startIndex; i < endIndex - 1; i++) {
            for (int j = i + 1; j < endIndex; j++) {
                if (chars[i] == chars[j]) {
                    int l1 = lengthOfLongestSubstring(chars, startIndex, j, max);
                    int l2 = lengthOfLongestSubstring(chars, j, endIndex, max);
                    if (l1 > l2) {
                        return l1;
                    } else {
                        return l2;
                    }
                }
            }
        }
        return endIndex - startIndex;
    }
}
上一篇 下一篇

猜你喜欢

热点阅读