求不重复的字符串长度

题目:

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

示例 1:

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

方法一:
class Solution {
    public int lengthOfLongestSubstring(String s) {
        
        int n=s.length();
        int ans=0;
        
        for(int i=0;i<n;i++)
            for(int j=i+1;j<n;j++)
            {
                if(allUnique(s,i,j)) ans=Math.max(ans, j-i);
            }
        return ans;
    }
    
    public boolean allUnique(String s,int start,int end)
    {
        Set<Character> set=new HashSet<>();
        
        for(int i=start;i<end;i++)
        {
            Character ch=s.charAt(i);
            if(set.contains(ch)) return false;
            set.add(ch);
        }
        return true;
    }
}

首先遍历所有的可能出现的字符串,使用二层循环;

然后再使用一个循环确定这个字符串是否重复(核心思想使用了集合,确定不重复元素)。

时间复杂度为O(n3)。

方法二:滑动窗口

class Solution {
    public int lengthOfLongestSubstring(String s) {
        
        Set<Character> set=new HashSet<>();
        int i=0,j=0,ans=0;
        int n=s.length();
        
        while(i<=n&&j<=n)
        {
            if(!set.contains(s.charAt(j)))
            {
                set.add(s.charAt(j++));
                ans=Math.max(ans, j-i);
            }
            else {
                set.remove(s.charAt(i++));
            }
        }
        return ans;
    }
}

使用滑动窗口,一些重复的的字符串比如ab,abc,abca,都有字符串ab,就不需要每一次都得重复检查。

时间复杂度为:O(n).

猜你喜欢

转载自www.cnblogs.com/Optimism/p/10712860.html