Decode String — Stack for Counts and Strings
Advertisement
Problem 268 · Decode String
Difficulty: Medium · Pattern: Two-Stack (counts + strings)
Decode k[encoded_string] format, possibly nested.
Solutions
# Python
def decodeString(s):
stack = [] # (current_string, current_count)
cur_str = ''
cur_num = 0
for c in s:
if c.isdigit():
cur_num = cur_num * 10 + int(c)
elif c == '[':
stack.append((cur_str, cur_num))
cur_str = ''; cur_num = 0
elif c == ']':
prev_str, num = stack.pop()
cur_str = prev_str + num * cur_str
else:
cur_str += c
return cur_str
// Java
public String decodeString(String s) {
Deque<Integer> counts = new ArrayDeque<>();
Deque<StringBuilder> strings = new ArrayDeque<>();
StringBuilder cur = new StringBuilder(); int k = 0;
for (char c : s.toCharArray()) {
if (Character.isDigit(c)) k = k*10 + c-'0';
else if (c == '[') { counts.push(k); strings.push(cur); cur = new StringBuilder(); k=0; }
else if (c == ']') {
int n = counts.pop(); StringBuilder prev = strings.pop();
for (int i=0;i<n;i++) prev.append(cur); cur = prev;
} else cur.append(c);
}
return cur.toString();
}
// C++
string decodeString(string s) {
stack<int> counts; stack<string> strings;
string cur; int k = 0;
for (char c : s) {
if (isdigit(c)) k=k*10+c-'0';
else if (c=='[') { counts.push(k); strings.push(cur); cur=""; k=0; }
else if (c==']') {
int n=counts.top(); counts.pop();
string prev=strings.top(); strings.pop();
for (int i=0;i<n;i++) prev+=cur; cur=prev;
} else cur+=c;
}
return cur;
}
Complexity
- Time: O(output size)
- Space: O(n)
Advertisement