Skip to content

Instantly share code, notes, and snippets.

@yehee
Last active October 8, 2019 06:29
Show Gist options
  • Save yehee/cd7c9a6ade35ef57efa93247a255f3b9 to your computer and use it in GitHub Desktop.
Save yehee/cd7c9a6ade35ef57efa93247a255f3b9 to your computer and use it in GitHub Desktop.
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