获取给定字符串最长不重复子串

一开始的思路就是暴力解决法:获取所有的子串,写一个可以判断字符串是否有重复字符的函数,来排除重复字符串的可能,没找到一个无重复字符的子串,记录长度,找出最大长度的子串即可,这里只记录最大长度:

class Solution {
    public boolean isRepeat(char[] subStr, char curChar, int length)
    {
        boolean b = false;
        for(int i = 0; i < length; i++)
        {
            if(subStr[i] == curChar)
            {
                b = true;
                break; 
            }
        }
        return b;
    } 
    public int lengthOfLongestSubstring(String s) {
        int length = s.length();
        char[] subStr = new char[300];
        int curSubL = 0, result = 0;
        for(int i = 0; i < length; i++)
        {
            for(int j = i; j < length; j++)
            {
                if(curSubL == 0 || isRepeat(subStr, s.charAt(j), curSubL) == false)
                {
                    subStr[curSubL] = s.charAt(j);
                    curSubL++;
                    if(curSubL > result)
                    {
                        result = curSubL;
                    }
                }
                else
                {
                    curSubL = 0;
                    break;
                }
            }
        }
        return result;
    }
}

还有一种拉窗帘解法,想象从下标i到j的子串,如果该子串已经是无重复字符子串,如果新加一个下标j+1字符,跟i~j子串有重复字符,则直接去掉下标i对应字符,判断i+1到j+1即可。代码如下:

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

猜你喜欢

转载自blog.csdn.net/m0_37907835/article/details/79719418