DAY 2 LC:求最长无重复字符串的子串长度

题目描述:
Given a string, find the length of the longest substring without repeating characters.

Examples:
Given “abcabcbb”, the answer is “abc”, which the length is 3.
Given “bbbbb”, the answer is “b”, with the length of 1.
Given “pwwkew”, the answer is “wke”, with the length of 3. Note that the answer must be a substring, “pwke” is a subsequence and not a substring.
给定一个字符串,要求求出其中无重复字符的最长子串,
caution:子串是指连续的字符串。
1 暴力求解法
即求解所有满足条件的子串,从中找出一个最长子串。

class Solution {
    public int lengthOfLongestSubstring(String s) {
        int ans=0;
        int n=s.length();
        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);//charAt返回字符串中第i个字符
            if (set.contains(ch)) return false;//contains判断ch是否已经存在于集合set中,set是无重复元素的结构。
            set.add(ch);
        }
        return true;
    }
}//判断字符串是否满足无重复字母的条件

结果提交上去之后显示超时,果然暴力法这种解法效率太低了,时间复杂度为O(n^3),心有不甘,
自己又写了个代码,类似于答案的滑动窗口,但不知道为什么就是卡死在” “这个字符串上就是AC不了,难受
下面这个方法较容易理解

class Solution {
    public int lengthOfLongestSubstring(String s) {
        int n =s.length();
        int ans=0;
        Set<Character> set =new HashSet();
        int i=0,j=0;
        while(j<n&&i<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;
    }
}

我们使用 HashSet 将字符存储在当前窗口 [i, j)[i,j)(最初 j = ij=i)中。 然后我们向右侧滑动索引 j,如果它不在 HashSet 中,我们会继续滑动 jj。直到 s[j] 已经存在于 HashSet 中。此时,我们找到的没有重复字符的最长子字符串将会以索引 ii 开头。

猜你喜欢

转载自blog.csdn.net/shine10076/article/details/82290793