3. Longest Substring Without Repeating Characters

description:

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

Example:

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.

my answer:

class Solution {
public:
    int lengthOfLongestSubstring(string s) {
        int res = 0, n = s.size(), left = -1;
        unordered_map<int, int>m;
        for (int i = 0; i < n; i++){
            if(m.count(s[i]) && m[s[i]] > left){
                left = m[s[i]];
            }
            m[s[i]] = i;
            res = max(res, i - left);
        }
        return res;
    }
};

relative point get√:

  • subsequence and not a substring, subsequence可以不挨着不连续

hint :

给定array,建立哈希表unordered_map<array[i], i>是一种常用的手段,可用作是否重复的标记,即检查是否已经在这个哈希表中

这道题的思路是说,从左到右依次找出所有不重复的尽可能长的子串。在这里是维持一个滑动串口,右边每移动一下就判断一下这个要加进窗口的数是不是已经在窗口里了,如果在窗口里就把左边的窗框缩到和他一样的那个数的下一个。整个过程的窗口就像是一条毛毛虫,一会拉长一会缩短的往终点爬,这个过程会出现一个最大的长度即所求。

原文地址:https://www.cnblogs.com/forPrometheus-jun/p/10443260.html