classSolution { public: intlengthOfLongestSubstring(string s){ int n=s.length(); //用来保存每个字符的下一个位置,用于出现重复字符的时候直接赋值给i int cNum[128]={0}; intmax=0; //i是第一个指针,j是第二个 for(int j=0,i=0;j<n;j++){ //如果不为0就是出现了和s[j]一样的字符,让i等于那个字符的后一个位置 if(cNum[s[j]]){ i = cNum[s[j]]>i?cNum[s[j]]:i; } //这里不管有没有重复字符都要更新max和cNum[s[j]] //很明显,如果有,i已经被更新,相当于已经变成了没有重复字符的情形,位置也要更新 max=(j-i+1)>max?(j-i+1):max; cNum[s[j]]=j+1; } returnmax; }
};
Python Codes
用时52ms,12.7MB
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15
classSolution(object): deflengthOfLongestSubstring(self, s): """ :type s: str :rtype: int """ cNum=dict() res=0 start=0 for i in range(len(s)): if s[i] in cNum: start=max(start,cNum[s[i]]) res=max(res,i-start+1) cNum[s[i]]=i+1 return res