classSolution { public: intcharacterReplacement(string s, int k){ int len = s.size(); int res = 0; int j, a; for(int i = 0; i < len; i++) { char c = s[i]; a = k; for(j = i+1;j < len; j++) { if (c != s[j]) { if (a == 0) break; else a--; } } res = max(j-i, res); } for(int i = 0;i < k && i+1 < len; i++) { char c = s[i+1]; a = k-i-1; for(j = i + 2;j < len; j++) { if (c != s[j]) { if (a == 0) break; else a--; } } res = max(j-i, res); } return res; } };
OK,现在可以忽略掉上面的解法了,看看O(n)的解法是怎样的:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19
classSolution { public: intcharacterReplacement(string s, int k){ vector<int> ch(26); int start = 0, end = 0, max_count = 0; int len = s.size(); while(end < len) { ch[s[end] - 'A']++; // update max_count max_count = max(max_count, ch[s[end]-'A']); end++; if ( end - start > max_count + k) { ch[s[start] - 'A']--; start++; } } return end - start; } };