Leetcode:3. 无重复字符的最长字符串

Leetcode:3. 无重复字符的最长字符串

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

示例 1:

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

示例 2: 

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

示例 3:

输入: "pwwkew"
输出: 3
解释: 因为无重复字符的最长子串是 "wke",所以其长度为 3。

AC代码,未优化滑动窗口算法:

class Solution {
    public static int lengthOfLongestSubstring(String s) {
        int[] index = new int[128];
        int left = 0;
        int right = 0;
        int ans = 0;
        while(right < s.length()){
            if(index[s.charAt(right)] == 0){
                ++index[s.charAt(right)];
                ++right;
            }
            else{
                ans = Math.max(ans,right - left);
                if(right + 1 != s.length() && s.charAt(right) == s.charAt(right + 1)){
                    //清空数组
                    for(int i=left;i!=right;++i){
                        --index[s.charAt(i)];
                    }
                    while(right + 1 != s.length() && s.charAt(right) == s.charAt(right + 1)){
                        ++right;
                    }
                    left = right;
                    continue;
                }
                --index[s.charAt(left)];
                ++left;
            }
            if(right == s.length()){
                ans = Math.max(ans,right - left);
            }
        }
        return ans;
    }
}

解法2:暴力解法:

class Solution {
    public int lengthOfLongestSubstring(String s) {
        Set<Character> stores;
        int ans = 0;
        int n = s.length();
        boolean hasDuplicate;
        for(int i=0;i<n;++i){
            for(int j=i + 1;j<=n;++j){
                stores = new HashSet<>();
                hasDuplicate = true;
                for(int k=i;k<j;++k){
                    if(stores.contains(s.charAt(k))){
                        hasDuplicate = false;
                        break;
                    }
                    else{
                        stores.add(s.charAt(k));
                    }
                }
                if(hasDuplicate)
                    ans = Math.max(ans,j - i);
            }
        }
        return ans;
    }
}

解法3:优化滑动窗口算法:

class Solution {
    public int lengthOfLongestSubstring(String s) {
        int n = s.length();
        Set<Character> set = new HashSet<>();
        int ans = 0;
        int start = 0;
        int end= 0;
        while(start < n && end < n){
            if(set.contains(s.charAt(end))){
                set.remove(s.charAt(start++));
            }
            else{
                set.add(s.charAt(end++));
                ans = Math.max(ans,end - start);
            }
        }
        return ans;
    }
}
发布了2 篇原创文章 · 获赞 0 · 访问量 44

猜你喜欢

转载自blog.csdn.net/qq_33607393/article/details/104512407
今日推荐