用滑动窗口的思想来做。用一个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; } };
时间: 2024-10-07 02:07:17