首页 > 其他 > 详细

leetcode 3 Longest Substring Without Repeating Characters(滑动窗口)

时间:2015-10-21 14:05:02      阅读:276      评论:0      收藏:0      [点我收藏+]

用滑动窗口的思想来做。用一个unordered_map来查询之前的char有没有在现在的窗口中。

class Solution {
public:
    int lengthOfLongestSubstring(string s) {
        unordered_map<char,int>mp;
        int ans=0,now=0;//now is the window‘s instant length
        int b=0,e=0;//the window‘s begin and end
        int len=s.length();
        for(int i=0;i<len;i++){
            if(mp.count(s[i])==1&&mp[s[i]]>=b&&mp[s[i]]<e){//in the window
                b=mp[s[i]]+1;
                e=i+1;
                now=e-b;
                if(ans<now){
                    ans=now;
                }
                mp[s[i]]=i;
            }
            else{//not in the window
                mp[s[i]]=i;
                now++;
                e++;
                if(ans<now){
                    ans=now;
                }
            }
        }
        return ans;
    }
};

 

leetcode 3 Longest Substring Without Repeating Characters(滑动窗口)

原文:http://www.cnblogs.com/zywscq/p/4897481.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!