码迷,mamicode.com
首页 > 其他好文 > 详细

3. Longest Substring Without Repeating Characters

时间:2018-01-14 13:03:42      阅读:93      评论:0      收藏:0      [点我收藏+]

标签:tco   seq   must   cpp   ems   article   http   gpo   turn   

欢迎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;
    }
};

题目来源

3. Longest Substring Without Repeating Characters

标签:tco   seq   must   cpp   ems   article   http   gpo   turn   

原文地址:https://www.cnblogs.com/ranjiewen/p/8282566.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!