LeetCode刷题笔记--3. Longest Substring Without Repeating Characters

3. Longest Substring Without Repeating Characters

Medium

4867249FavoriteShare

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.

这道题调了很多遍,需要考虑到au,dvdf,abb这样的输入,比如右边界正好在结尾,这样的特殊情况。

class Solution {
public:
    int lengthOfLongestSubstring(string s) {
        //用两个指针在内部检查有没有重复,检查过的元素写到一个set中,查重用set.find()
        int len = s.length();
        int i = 0;
        int j = 1;
        if (len <= 1)return len;
        if((len==2)&&(s[0]==s[1]))return 1;
        if((len==2)&&(s[0]!=s[1]))return 2;
        set<int> t;
        int size = 0;
        t.insert(s[0]);
        while (j < len)
        {
            
                if (t.count(s[j]) == 0)
                {
                    t.insert(s[j]);
                    j++;
                    size = size < t.size() ? t.size(): size;
                }
                else
                {
                    size = size < t.size() ? t.size(): size;
                    i ++;
                    j =i+1;
                    t.clear();
                    t.insert(s[i]);
                }

        }
        return size;
    }
};

猜你喜欢

转载自blog.csdn.net/vivian0239/article/details/87970692
今日推荐