哈希表+双指针(效率较低)
class Solution {
public:
int lengthOfLongestSubstring(string s) {
int N=s.length();
if(N<=0)return 0;
map<char,int>mmp;
int R=0;
int L=0;
int maxLength=0;
while(R<N&&L<=R)
{
if(mmp[s[R]]==0)
{//若表没有该元素,直接右指针++;
++mmp[s[R]];
++R;
maxLength=max(maxLength,R-L);
}
else if(mmp[s[R]]>0)
{//若表中有该元素,左指针加一;
--mmp[s[L]];
++L;
}
}
return maxLength;
}
};
优化版:
class Solution {
public:
int lengthOfLongestSubstring(string s) {
vector<int>vec(128,-1);
int left=-1;
int maxLength=0;
for(int i=0;i<s.size();++i)
{
left=max(left,vec[s[i]]);//比较新的定位跟旧定位是否更新
vec[s[i]]=i;//将位置更新
maxLength=max(maxLength,i-left);//更新最长不重复字串的长度
}
return maxLength;
}
};