用hash记录每个字符上次出现的位置。
如果这个字符上次出现的位置比我们要的字符串起点要后面,则把这个位置更新为我们要的字符串起点,然后比较最大长度。
hash表长度为256。(ASCII码)
class Solution {
public:
int lengthOfLongestSubstring(string s) {
int len=s.length();
if(len==0)return 0;
int local[256];
memset(local,-1,sizeof(local));
int max=0,index=-1;
for(int i=0;i<len;i++)
{
if(local[s[i]]>index)//更新起点
index=local[s[i]];
if(i-index>max)
max=i-index;
local[s[i]]=i;
}
return max;
}
};