LeetCode 3: Longest Substring Without Repeating Characters

Posted alpaca

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了LeetCode 3: 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.


描述:

给定一个字符串,返回该字符串最长无重复子串,即最长的不包含重复字符的子字符串。

示例:

给定字符串 “abcabcbb”, 答案为 “abc”,长度为3;
给定字符串 “bbbb”, 答案为 “b”, 长度为1;
给定字符串 “pwwkew”, 答案为 “wke”,长度为3. 注意,答案必须为子串,“pwke”是子序列,但不是子字符串。

 

方法一:暴力破解

遍历字符串的每个子串,并判断相应子串中是否存在重复字符。

class Solution {
public:
    int lengthOfLongestSubstring(string s) {
        if(s.length() == 0) {
            return 0;
        }
        int maxLen = 0;
        for(int i = 0; i < s.length(); i++) {
            for(int j = i + 1; j < s.length() + 1; j++) {
                if(hasRepeatChar(s, i, j)) {
                    break;
                }
                int len = j - i;
                if(len > maxLen) {
                    maxLen = len;
                }
            }
        }
        return maxLen;
    }
    
    bool hasRepeatChar(string s, int start, int end) {
        set<int> c;
        for(int i = start; i < end; i++) {
            if(c.count(s[i]) != 0) {
                return true;
            }
            c.insert(s[i]);
        }
        return false;
    }
};

该方法的时间复杂度为O(n3),空间复杂度为O(n)。

然而,该方法时间复杂度较高,导致Time Limit Exceeded.

 

方法二:滑动窗口

 

以上是关于LeetCode 3: Longest Substring Without Repeating Characters的主要内容,如果未能解决你的问题,请参考以下文章

Leetcode 3. Longest Substring Without Repeating Characters

LeetCode 3. Longest Substring Without Repeating

3. 没有重复字母的最长子串 [leetcode 3: Longest Substring Without Repeating Characters]

3. 没有重复字母的最长子串 [leetcode 3: Longest Substring Without Repeating Characters]

leetcode longest consecutive sequence

leetcode 3. Longest Substring Without Repeating Characters (Python版)