1
0
Fork 0
mirror of https://gitlab.com/mfocko/LeetCode.git synced 2024-09-19 17:56:55 +02:00
LeetCode/java/decode-string.java

36 lines
859 B
Java
Raw Normal View History

import java.util.Stack;
class Solution {
private record StackEntry(int count, StringBuilder str) {
@Override
public String toString() {
return new StringBuilder().repeat(str(), count()).toString();
}
}
public String decodeString(String s) {
var stack = new Stack<StackEntry>();
stack.push(new StackEntry(1, new StringBuilder()));
int count = 0;
for (int i = 0; i < s.length(); ++i) {
var c = s.charAt(i);
if (c == '[') {
stack.push(new StackEntry(count, new StringBuilder()));
count = 0;
} else if (c == ']') {
var last = stack.pop();
stack.peek().str().append(last);
} else if (Character.isDigit(c)) {
count *= 10;
count += c - '0';
} else {
stack.peek().str().append(c);
}
}
return stack.pop().toString();
}
}