Intuition
[...] segments can nest. When we hit [, we freeze the current state (the
string built so far and the multiplier) on a stack, and start a fresh inner
build. When we hit ], we pop and splice the inner k times into the parent.
Explanation
Approach
Maintain curr_str and curr_k (the number just being parsed).
| Char | Action |
|---|---|
| digit | accumulate into curr_k |
[ | push (curr_str, curr_k), reset both |
] | prev_str, k = pop; curr_str = prev_str + k * curr_str |
| letter | append to curr_str |
Implementation
import java.util.*;
class Solution {
public String decodeString(String s) {
Deque<String> strStack = new ArrayDeque<>();
Deque<Integer> countStack = new ArrayDeque<>();
StringBuilder curr = new StringBuilder();
int k = 0;
for (char c : s.toCharArray()) {
if (Character.isDigit(c)) {
k = k * 10 + (c - '0');
} else if (c == '[') {
strStack.push(curr.toString());
countStack.push(k);
curr = new StringBuilder();
k = 0;
} else if (c == ']') {
String prev = strStack.pop();
int repeat = countStack.pop();
StringBuilder tmp = new StringBuilder(prev);
for (int i = 0; i < repeat; i++) {
tmp.append(curr);
}
curr = tmp;
} else {
curr.append(c);
}
}
return curr.toString();
}
}