mirror of
https://gitlab.com/mfocko/LeetCode.git
synced 2024-11-09 15:59:06 +01:00
java: add «394. Decode String»
Signed-off-by: Matej Focko <me@mfocko.xyz>
This commit is contained in:
parent
c34927bd88
commit
a31b0d7cdf
1 changed files with 35 additions and 0 deletions
35
java/decode-string.java
Normal file
35
java/decode-string.java
Normal 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();
|
||||||
|
}
|
||||||
|
}
|
Loading…
Reference in a new issue