Skip to content

Instantly share code, notes, and snippets.

@alice-0-kim alice-0-kim/leetcode.java
Last active Oct 8, 2019

Embed
What would you like to do?
class Solution {
private boolean isDigit(String s) {
return s.matches("\\d");
}
private String generate(String unit, int times) {
StringBuilder sb = new StringBuilder();
while (times > 0) {
sb.append(unit);
times--;
}
return sb.toString();
}
public String decodeString(String s) {
Deque<String> deque = new ArrayDeque<>();
int i = 0; // current index
StringBuilder sb = new StringBuilder();
while(i < s.length()) {
char c = s.charAt(i);
if (c == ']') {
String unit = "", numString = "";
while(!deque.peek().equals("[")) {
unit = deque.pop() + unit;
}
deque.pop();
while(!deque.isEmpty() && isDigit(deque.peek())) {
numString = deque.pop() + numString;
}
int times = Integer.parseInt(numString);
deque.push(generate(unit, times));
} else {
deque.push(Character.toString(c));
}
i++;
}
while(!deque.isEmpty()) sb.insert(0, deque.pop());
return sb.toString();
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.