Leetcode刷题小记(3)--T3

3. Longest Substring Without Repeating Characters

 

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.

 答案:

class Solution {
public:
       int lengthOfLongestSubstring(string &s) {
        
        unordered_set visited;
        
        int slow = 0, fast = 0, ans = 0;
        
        while (fast < s.size()) {
            if (visited.find(s[fast]) == visited.end()) {
                visited.insert(s[fast]);
                ++fast;
                ans = max(ans, fast - slow);
                continue;
            }
            visited.erase(s[slow++]);
        }
        
        return ans;
    }
};

虽然这样速度不是特别快,但比较好理解。主要是借助STL库中的hashSet,来记录走过的字母

当fast指向的当前字母没走过,则fast指针勇敢地往前走,hashSet记录一下其走过的char;
当fast指向的当前字母走过,则slow指针往前挪、并且把slow走过的char从hashSet中移除。

~~

你可能感兴趣的:(算法)