LeetCode-3无重复字符的最长子串

class Solution {
public:
    int lengthOfLongestSubstring(std::string s)
    {
        std::map<char, size_t> map;
        std::map<char, size_t>::iterator iter;
        size_t length = s.length();
        size_t max = 0;
        size_t start = 0;
        size_t candidate = 0;

        for (size_t i = 0; i < length; ++i)
        {
            iter = map.find(s[i]);
            if (iter != map.end() and start <= map[s[i]])
            {
                start = map[s[i]]+1;
            }
            else
            {
                candidate = i-start+1;
                if (max < candidate)
                {
                    max = candidate;
                }
            }

            map[s[i]] = i;
        }

        return max;
    }
};

第二种方法:

class Solution {
public:
    int lengthOfLongestSubstring(string s) {
        map<char,int>m;
        int last=-1;
        int maxLen=0;
        for(int i=0;i<s.size();i++)
        {
            if(m.find(s[i])!=m.end()&&last<m[s[i]])//m.find(s[i])指如果在m中查找到与s[i]相同的字符串后,返回与s[i]相同的第一个字符第一次所在的位置//.end指向最后一个末尾
            {
                last=m[s[i]];//将key保存到last中
            }
            maxLen=max(maxLen,i-last);
            m[s[i]]=i;
        }
        return maxLen;
    }
};
//直观的一个理解就是从头往后,定义一个hash表,存入字符以及具体索引值,当发现找到已经存在的字符的时候,但注意,一定要是上一个重复的
    //点的索引值在这个重复点之前  比如 a b b a
    //在没有遇到重复点之前,所有的按计划操作,,等到出现重复字符的时候,
    //把上一次的索引值保存在last里面,这个时候的i - lastRepeatPos一般不会大于maxLen 的,除非start就在隔壁。
    //而且这个有一个好处就是,在没有出现重复字符之前,它能够自动更新。
    //当然这里面涉及一个+1和-1的问题,虽然保存last=m[s[i]];但是实际上需要一个+1再-1的计算

猜你喜欢

转载自blog.csdn.net/qq_42020563/article/details/80341844