https://leetcode.com/problems/decode-string/
- Stack
- String
Use stacks for counts and partial strings to handle nested encoded segments.
O(n)
O(n)
import java.util.*;
class Solution {
public String decodeString(String s) {
Stack<Integer> counts = new Stack<>();
Stack<StringBuilder> strings = new Stack<>();
StringBuilder curr = new StringBuilder();
int num = 0;
for (char c : s.toCharArray()) {
if (Character.isDigit(c)) {
num = num * 10 + (c - '0');
} else if (c == '[') {
counts.push(num);
strings.push(curr);
curr = new StringBuilder();
num = 0;
} else if (c == ']') {
int count = counts.pop();
StringBuilder prev = strings.pop();
for (int i = 0; i < count; i++) prev.append(curr);
curr = prev;
} else {
curr.append(c);
}
}
return curr.toString();
}
}