1
0
Fork 0
mirror of https://gitlab.com/mfocko/LeetCode.git synced 2024-09-16 16:36:56 +02:00

java: add «394. Decode String»

Signed-off-by: Matej Focko <me@mfocko.xyz>
This commit is contained in:
Matej Focko 2024-08-23 22:56:22 +02:00
parent c34927bd88
commit a31b0d7cdf
Signed by: mfocko
SSH key fingerprint: SHA256:icm0fIOSJUpy5+1x23sfr+hLtF9UhY8VpMC7H4WFJP8

35
java/decode-string.java Normal file
View file

@ -0,0 +1,35 @@
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();
}
}