1
0
Fork 0
mirror of https://gitlab.com/mfocko/LeetCode.git synced 2024-11-09 15:59:06 +01:00
LeetCode/java/decode-string.java
Matej Focko a31b0d7cdf
java: add «394. Decode String»
Signed-off-by: Matej Focko <me@mfocko.xyz>
2024-08-23 22:56:22 +02:00

35 lines
859 B
Java

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();
}
}