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
| class Solution { public int maximumLength(String s) { List<Integer>[] groups = new ArrayList[26]; for (int i = 0; i < 26; i++) { groups[i] = new ArrayList<>(); }
int length = 0; for (int i = 0; i < s.length(); i++) { length++; if (i + 1 == s.length() || s.charAt(i) != s.charAt(i + 1)) { groups[s.charAt(i) - 'a'].add(length); length = 0; } }
int ans = 0; for (List<Integer> lengthList : groups) { if (lengthList.isEmpty()) { continue; } lengthList.sort(Collections.reverseOrder()); lengthList.add(0); lengthList.add(0); ans = Math.max(ans, Math.max(lengthList.get(0) - 2, Math.max(Math.min(lengthList.get(0) - 1, lengthList.get(1)), lengthList.get(2)))); } return ans > 0 ? ans : -1; } }
|
References
2982. Find Longest Special Substring That Occurs Thrice II