题目链接:Longest Substring Without Repeating Characters

Given a string, find the length of the longest substring without repeating characters. For example, the longest substring without repeating letters for “abcabcbb” is “abc”, which the length is 3. For “bbbbb” the longest substring is “b”, with the length of 1.

这道题的要求是在字符串中找到最长无重复字符的子串的长度。

直接思路,暴力搜索,对于每个子串都检查是否包含重复字符,时间复杂度O(n3)。

优化一下,使用l和r两个指针维护子串,用Hash表记录字串中出现的字符。每次循环r右移1位,然后判断r右移之后所指向的字符是否在Hash表中出现过:如果出现过,则表示出现重复字符,记录该子串长度,并与最长长度比较,然后逐步右移l并在Hash表中删除l指向的字符直到没有重复字符出现;如果没出现过,则说明没有重复字符,将该字符放入Hash表。

至于Hash表的建立,如果只有小写字母或是ASCII码,可以用一个数组实现。当然,也可以采用更广泛的set或是unordered_set实现。

时间复杂度:O(n)

空间复杂度:O(m)(取决于不同字符数量)

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
class Solution
{
public:
    int lengthOfLongestSubstring(string s)
    {
        if(s == "")
            return 0;
        
        int l = 0, r = 0, maxl = 0;
        set<char> cset;
        
        while(r < s.size())
        {
            if(cset.find(s[r]) == cset.end())
                cset.insert(s[r]);
            else
            {
                maxl = max(maxl, r - l);
                while(s[r] != s[l])
                {
                    cset.erase(s[l]);
                    ++ l;
                }
                ++ l;
            }
            ++ r;
        }
        maxl = max(maxl, r - l);
        
        return maxl;
    }
};