3. Longest Substring Without Repeating Characters

欢迎fork and star:Nowcoder-Repository-github

3. Longest Substring Without Repeating Characters

题目

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.

解析

  • solution思路循序渐进,很值得思考!
  • 对找到元素后更新位置处理,i取max(mp[s[j]] ,i)细节处理。
class Solution_3 {
public:
    int lengthOfLongestSubstring(string s) {

        if (s.size()==0)
        {
            return 0;
        }

        int ret = 0;
        map<char, int> mp;
        int i = 0;
        for (int j = 0; j < s.size();j++)
        {
            if (mp.count(s[j])) //找到了,没有插入当前元素,之前插入的相同元素充当当前元素,但要覆盖当前元素的位置second,//或者覆盖
            {
                ret = max(ret, j - i);

                if (mp[s[j]]>=i) //有可能返回去 "abba"
                {
                    i = mp[s[j]] + 1; //下次从第一次个重复的下一个位置开始
                }

                mp[s[j]] = j; //更新位置
                
            }
            else
            {
                mp.insert(make_pair(s[j],j));
            }
        }
        ret = ret > (s.size() - i) ? ret : (s.size() - i); // 尾处理

        return ret;
    }
};

题目来源

    原文作者:ranjiewen
    原文地址: https://www.cnblogs.com/ranjiewen/p/8282566.html
    本文转自网络文章,转载此文章仅为分享知识,如有侵权,请联系博主进行删除。
点赞