标签:
用滑动窗口的思想来做。用一个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