标签:
用sliding window的方法,之前还有个k不同元素好像也是类似的思路。有时间可以去复习下。
https://leetcode.com/problems/longest-repeating-character-replacement/ // sliding window public class Solution { public int characterReplacement(String s, int k) { int[] count = new int[26]; int maxch = -1; // the char with max count in current substr int max = 0; // the max count for single char in current substr int len = 0; // current substr length int ret = 0; // final result for (int i=0; i<s.length(); i++) { int tmp = s.charAt(i) - ‘A‘; count[tmp]++; len++; if (maxch == tmp) { max++; } else { if (count[tmp] > max) { max = count[tmp]; maxch = tmp; } } if (len - max <= k) { if (len > ret) { ret = len; } } while (len - max > k) { int newTmp = s.charAt(i-len+1) - ‘A‘; count[newTmp]--; len--; if (maxch == newTmp) { max--; for (int j=0; j<26; j++) { if (count[j] > max) { max = count[j]; maxch = j; } } } } } return ret; } }
longest-repeating-character-replacement(难)
标签:
原文地址:http://www.cnblogs.com/charlesblc/p/5967989.html