无重复字符的最长子串

给定一个字符串 s ,请你找出其中不含有重复字符的 最长子串 的长度。

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

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

示例3:
输入: s = "pwwkew"
输出: 3
解释: 因为无重复字符的最长子串是 "wke",所以其长度为 3。
请注意,你的答案必须是 子串 的长度,"pwke" 是一个子序列,不是子串。

说明:
0 <= s.length <= 5 * 104
s 由英文字母、数字、符号和空格组成

暴力解法:

public int lengthOfLongestSubstring(String s){
        List<Character> list = new ArrayList<>();
        int size = s.length();
        int res = 0,slow = 0,fast = 0;
        while(fast < size){
            if(!list.contains(s.charAt(fast))){
                list.add(s.charAt(fast));
                fast++;
            }else{
                list.clear();
                slow++;
                fast = slow;
            }
            res = Math.max(res,fast - slow);
        }
        return res;
}
    

优化1:

public int lengthOfLongestSubstring(String s){
        int[] arr = new int[256];
        int size = s.length();
        int res = 0,slow = 0,fast = 0;
        while(fast < size){
            int index = s.charAt(fast) - 0;
            arr[index] += 1;
            fast++;
            while(arr[index] > 1){
                int index1 = s.charAt(slow) - 0;
                slow++;
                arr[index1] -= 1;
            }
            res = Math.max(res,fast - slow);
        }
        return res;
    }

优化2:

public int lengthOfLongestSubstring(String s){
        int size = s.length(), res = 0, start = 0, end = 0;
        Map<Character, Integer> mp = new HashMap<>();
        while(end < size){
            char tmp = s.charAt(end);
            if (mp.containsKey(tmp)) {
                start = Math.max(mp.get(tmp), start);
            }
            res = Math.max(res, end - start + 1);
            mp.put(s.charAt(end), end + 1);
            end++;
        }
        return res;
    }

 

posted @ 2022-09-08 16:15  码到成功hy  阅读(13)  评论(0编辑  收藏  举报
获取

hahah

name age option