- Translate each rule into one explicit state update.
- Maintain the invariant after every processed item.
- Return the accumulated state once all relevant input has been handled.
Code notes
- 36 lines of Java from the credited upstream file 2182.java.
- The implementation visibly relies on sequence storage.
- 4 loop blocks detected.
Complexity
Count the number and nesting of passes over the input, then include the maintained containers in the memory estimate.
Check the problem constraints before deciding whether this complexity will pass.
Use this to learn the idea, then write your own version.
1class Solution {2 public String repeatLimitedString(String s, int repeatLimit) {3 StringBuilder sb = new StringBuilder();4 int[] count = new int[26];5 6 for (final char c : s.toCharArray())7 ++count[c - 'a'];8 9 while (true) {10 final boolean addOne = !sb.isEmpty() && shouldAddOne(sb, count);11 final int i = getLargestChar(sb, count);12 if (i == -1)13 break;14 final int repeats = addOne ? 1 : Math.min(count[i], repeatLimit);15 sb.append(String.valueOf((char) ('a' + i)).repeat(repeats));16 count[i] -= repeats;17 }18 19 return sb.toString();20 }21 22 private boolean shouldAddOne(StringBuilder sb, int[] count) {23 for (int i = 25; i >= 0; --i)24 if (count[i] > 0)25 return sb.charAt(sb.length() - 1) == 'a' + i;26 return false;27 }28 29 private int getLargestChar(StringBuilder sb, int[] count) {30 for (int i = 25; i >= 0; --i)31 if (count[i] > 0 && (sb.isEmpty() || sb.charAt(sb.length() - 1) != 'a' + i))32 return i;33 return -1;34 }35}36