【LeetCode】3. Longest Substring Without Repeating Characters

Description:

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

Examples:

Given "abcabcbb", the answer is "abc", which the length is 3.

Given "bbbbb", the answer is "b", with the length of 1.

Given "pwwkew", 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.

题目就是让我们找到最长的无重复元素的子序列。

    我们可以用start记录子字符串开始位置,index记录当前位置,如果遇到重复元素,就将start更新为重复元素的下一个位置,并将重复元素和它之前的字符串都删除掉。

    但是我们可以避免将字符串删除,如果重复元素第一次出现的位置比i大,那就把start更新为重复元素第一次出现的下一个位置,否则start将维持原来的值。

class Solution {
public:
    int lengthOfLongestSubstring(string s) {
        if(s.size()==1)
            return 1;

        map<char, int> map_s;
        int maxLength=0,start=0,index=0;
        map_s.insert(pair<char,int>(s[0], 0));
        
        for(int i=1;i<s.length();i++){
            if(map_s.count(s[i])){//如果遇到重复元素
                start=max(map_s[s[i]]+1,start);//start的位置从重复元素第一次出现的下一个位置开始计,
                                                //但同时要保证start大于第一次出现重复元素的位置   例如abba字符串
                map_s[s[i]]=i;
            }
            else{
                map_s.insert(pair<char,int>(s[i], i));    
            }
                          
            index = i;
            maxLength = max(maxLength,index-start+1);
        }
        return maxLength;
        
    }
};


注意几个地方:

map变量想要改变value值,应该采用直接赋值的方法,不能用insert方法,insert不会改变原来的value值。

map_s.insert(pair<char,int>(s[i], i));//map的插入形式


猜你喜欢

转载自blog.csdn.net/poulang5786/article/details/79887098
今日推荐