算法

LeetCode3.无重复字符的最长子串

2021-07-28  本文已影响0人  Timmy_zzh
1.题目描述
示例 1:
输入: s = "abcabcbb"
输出: 3 
解释: 因为无重复字符的最长子串是 "abc",所以其长度为 3。

示例 2:
输入: s = "bbbbb"
输出: 1
解释: 因为无重复字符的最长子串是 "b",所以其长度为 1。

示例 3:
输入: s = "pwwkew"
输出: 3
解释: 因为无重复字符的最长子串是 "wke",所以其长度为 3。
     请注意,你的答案必须是 子串 的长度,"pwke" 是一个子序列,不是子串。
     
示例 4:
输入: s = ""
输出: 0
 
提示:
0 <= s.length <= 5 * 104
s 由英文字母、数字、符号和空格组成
2.解题思路:
    public int lengthOfLongestSubstring_v1(String s) {
        if (s == null || s.length() == 0) {
            return 0;
        }
        System.out.println(s);
        int len = s.length();
        ArrayList<String> list = new ArrayList<>();

        for (int start = 0; start < len; start++) {
            list.add(s.substring(start, start + 1));
            for (int end = start + 1; end < len; end++) {
                //已遍历过的子串[start,end)
                String subStr = s.substring(start, end);
                //判断新遍历的字符end,已便利字符串是否存在相同的字符
                if (subStr.contains(s.substring(end, end + 1))) {
                    break;
                }
                list.add(s.substring(start, end + 1));
            }
        }
        int res = 0;
        for (String str : list) {
            res = Math.max(res, str.length());
        }
        return res;
    }
    public int lengthOfLongestSubstring_v2(String s) {
        if (s == null || s.length() == 0) {
            return 0;
        }
        System.out.println(s);
        char[] chars = s.toCharArray();
        HashMap<Character, Integer> hashMap = new HashMap<>();
        int start = 0;
        int res = 0;
        for (int end = 0; end < chars.length; end++) {
            char endCh = chars[end];
            if (hashMap.containsKey(endCh)) {
                int preIndex = hashMap.get(endCh);
                //寻找不重复字符的开始位置
                start = start > preIndex ? start : preIndex + 1;
            }
            hashMap.put(endCh, end);
            res = Math.max(res, end - start + 1);
        }
        return res;
    }
    public int lengthOfLongestSubstring(String s) {
        if (s == null || s.length() == 0) {
            return 0;
        }
        System.out.println(s);
        int[] allChars = new int[128];
        Arrays.fill(allChars, -1);
        int start = 0;
        int res = 0;

        char[] chars = s.toCharArray();
        for (int end = 0; end < chars.length; end++) {
            char endCh = chars[end];
            if (allChars[endCh] != -1) {    //存在重复字符
                int preIndex = allChars[endCh];
                start = start > preIndex ? start : preIndex + 1;
            }
            allChars[endCh] = end;
            res = Math.max(res, end - start + 1);
        }
        return res;
    }
3.总结
上一篇下一篇

猜你喜欢

热点阅读