1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32
| class Solution { public int maxRepOpt1(String text) { Map<Character, Integer> countMap = new HashMap<>(); for (int i = 0; i < text.length(); i++) { countMap.put(text.charAt(i), countMap.getOrDefault(text.charAt(i), 0) + 1); }
int maxLength = 1;
for (int i = 0; i < text.length(); ) { char c = text.charAt(i);
int j = i; while (j < text.length() && text.charAt(j) == c) { j++; } int leftLength = j - i;
int k = j + 1; while (k < text.length() && text.charAt(k) == c) { k++; } int rightLength = k - (j + 1);
maxLength = Math.max(maxLength, Math.min(leftLength + 1 + rightLength, countMap.get(c))); i = j; }
return maxLength; } }
|
References
1156. Swap For Longest Repeated Character Substring