Skip to content

Instantly share code, notes, and snippets.

@wushbin
Created February 16, 2020 02:01
Show Gist options
  • Save wushbin/16cb4f2ebfffc07c1a1db88d4c4dad36 to your computer and use it in GitHub Desktop.
Save wushbin/16cb4f2ebfffc07c1a1db88d4c4dad36 to your computer and use it in GitHub Desktop.
class Solution {
public String decodeString(String s) {
if (s == null || s.length() == 0) {
return "";
}
return decode(s.toCharArray(), new int[]{0});
}
public String decode(char[] s, int[] p) {
StringBuilder result = new StringBuilder();
while(p[0] < s.length && s[p[0]] != ']') {
int count = 0;
while(p[0] < s.length && Character.isDigit(s[p[0]])) {
count = count * 10 + (s[p[0]] - '0');
p[0] += 1;
}
if (s[p[0]] == '['){
p[0] += 1; // skip /[
String inbucket = decode(s, p);
StringBuilder sb = new StringBuilder();
for (int i = 0; i < count; i++) {
sb.append(inbucket);
}
result.append(sb);
} else {
while(p[0] < s.length && !Character.isDigit(s[p[0]]) && s[p[0]] != ']') {
result.append(s[p[0]++]);
}
}
}
if (p[0] < s.length && s[p[0]] == ']') {
p[0]++;
}
return result.toString();
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment