classSolution { public: intlengthOfLongestSubstring(string s){ //滑动窗口裸题 //s 由英文字母、数字、符号和空格组成 ???????? if(s == ""){ return0; } s = ' ' + s; //cout << s << '\n'; int len = s.size(); int a[50010]; int tmp[300]; for(int i = 0 ; i < 300 ; i++){ tmp[i] = 0; } for(int i = 1 ; i < len ; i++) { //确定前一个相同字母位置 //cout << s[i] - 'a' << ' ' << tmp[s[i] - 'a'] <<"?\n"; if(tmp[s[i]] == 0){ a[i] = 0; tmp[s[i]] = i; } else { a[i] = tmp[s[i]]; tmp[s[i]] = i; } //cout << a[i] << '\n'; }
int ans = 1; int top, end; top = end = 1; for(int i = 2; i < len ; i++){ if(a[i] < top){ end++; ans = max(ans, end - top + 1); } elseif(a[i] == top){ top++; end++; ans = max(ans, end - top + 1); } else { top = a[i] + 1; end++; ans = max(ans, end - top + 1); } } return ans; } };