C++里面的hash表:unordered_map<>
class Solution {
public:
int longestSubstringWithoutDuplication(string s) {
unordered_map<char,int> hash; int res=0; for(int i=0,j=0;j<s.size();j++) { hash[s[j]]++; //cout<<"i=" <<i<<" "<<"j="<<j<<" "<< "s[j]="<<s[j]<<" "<<"hash[s[j]]="<<hash[s[j]]<< endl; while(hash[s[j]]>1)//j当前指向数字与前面的有重复 { /*把i位置上的字母删掉,并把i向后移动一位。下面一句代码实现这两个功能*/ //cout<<"i="<<i<<" "<< "s[i]="<<s[i]<<" "<<"hash[s[i]]=" <<hash[s[i]]<< endl; hash[s[i]]--;//把i位置上这字母s[i]从hash表中删掉。//例子:j=i--; 表示i先赋值给j,然后i在执行i=i-1; //cout<<"i="<<i<<" "<< "s[i]="<<s[i]<<" "<<"hash[s[i]]=" <<hash[s[i]]<< endl; i++; //执行完i++后,i向后移动一位,使得新的i到j之间所有字母只出现一次 } res=max(res,j-i+1); //cout<<"res=" <<res<< endl; } return res;
}
};