LeetCode-Longest Substring Without Repeating Characters

Description:
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.

题意:找出一个字符串中连续的且每个字符都只出现一次的子串;

第一种解法:最简单的方法就是暴力破解,遍历所有的可能,找出最大长度的那个;

class Solution {
    public int lengthOfLongestSubstring(String s) {
        int maxLen = 0;//最大长度变量
        for(int i=0; i<s.length(); i++){
            String str = "" + s.charAt(i);//不重复连续子串
            for(int j=i+1; j<s.length(); j++){
                if(str.indexOf(s.charAt(j)) != -1){
                    break;
                }
                str += s.charAt(j);
            }
            maxLen = str.length() > maxLen ? str.length() : maxLen;
        }
        return maxLen;
    }
}

第二种解法:我们采用滑动窗口的思想,定义区间[st, ed)为连续不重复字符的子串,当下个一字符在子串中不重复时,我们移动端点ed向右;当下一个字符在子串中重复时,我们移动端点st向右,直到不存在与下个字符相同的字符为止;

class Solution {
    public int lengthOfLongestSubstring(String s) {
        int maxLen = 0;
        Set<Character> table = new HashSet<>();
        int st, ed;//区间端点
        st = ed = 0;
        while(ed < s.length()){
            if(table.contains(s.charAt(ed))){
                table.remove(s.charAt(st++));
            }
            else{
                table.add(s.charAt(ed++));
                maxLen = ed-st > maxLen ? ed-st : maxLen;
            }
        }
        return maxLen;
    }
}

猜你喜欢

转载自blog.csdn.net/qq_24133491/article/details/80925563