美文网首页
3. Longest Substring Without Rep

3. Longest Substring Without Rep

作者: syuhung | 来源:发表于2020-06-09 18:21 被阅读0次

    Given a string, find the length of the longest substring without repeating characters.

    Example 1:
    Input: "abcabcbb"
    Output: 3
    Explanation: The answer is "abc", with the length of 3.

    Example 2:
    Input: "bbbbb"
    Output: 1
    Explanation: The answer is "b", with the length of 1.

    Example 3:
    Input: "pwwkew"
    Output: 3
    Explanation: 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.


    题目大意:

      给定一个字符串,找到无重复字符的最长子串的长度。
      提示:是找子串而不是子序列。

    解题思路:

      第一,要找到最长,肯定得把字符串遍历完。第二,题目限定不可重复,很容易想到一个对应的数据结构——set。具体思路是遍历字符串,检查当前字符串是否在set里面,如果不存在则插入set,并且将当前set的长度与最长串的长度作比较,取最大值;如果set里已存在该字符,基于set结构的不重复特性,逐渐从开头删除字符直到无相同字符。

    解题代码:

    
    class Solution {
    public:
      int lengthOfLongestSubstring(string s)
      {
        set<char> t;
        int res = 0;
        for (int i = 0,j = 0; i < s.size(); ++i)
        {
            if (t.find(s[i]) == t.end())
            {
                t.insert(s[i]);
                res = max(res, (int)t.size());
            }
            else
            {
                t.erase(s[j++]);
            }
        }
        return res;
      }
    };
    

    相关文章

      网友评论

          本文标题:3. Longest Substring Without Rep

          本文链接:https://www.haomeiwen.com/subject/ggcuahtx.html