Skip to content

Instantly share code, notes, and snippets.

@zsolt-donca
Created February 23, 2017 10:45
Show Gist options
  • Save zsolt-donca/0a1863ac94a38b8ab2e495b673cf511e to your computer and use it in GitHub Desktop.
Save zsolt-donca/0a1863ac94a38b8ab2e495b673cf511e to your computer and use it in GitHub Desktop.
Java solution to the string decoding problem: https://leetcode.com/problems/decode-string/
import java.util.function.Predicate;
import java.util.stream.Stream;
public class Solution {
private int indexOfPred(String s, Predicate<Character> p) {
for (int i = 0; i < s.length(); i++) {
if (p.test(s.charAt(i))) {
return i;
}
}
return -1;
}
private int endIndexOfGroup(String s) {
assert s.charAt(0) == '[';
int depth = 1;
for (int i = 1; i < s.length(); i++) {
char c = s.charAt(i);
if (c == '[') depth += 1;
else if (c == ']') depth -= 1;
if (depth == 0) {
return i;
}
}
throw new RuntimeException("Unmatching end parentheses in string: " + s);
}
private String repeatString(int count, String decodedParen) {
return Stream.generate(() -> decodedParen)
.limit(count)
.reduce("", String::concat);
}
public String decodeString(String s) {
if (s.isEmpty()) {
return "";
}
if (Character.isDigit(s.charAt(0))) {
int parenIndex = s.indexOf('[');
String digits = s.substring(0, parenIndex);
int count = Integer.parseInt(digits);
String parenAndRest = s.substring(parenIndex);
int endIndex = endIndexOfGroup(parenAndRest);
String parenUnpacked = parenAndRest.substring(1, endIndex);
String rest = parenAndRest.substring(endIndex + 1);
String decodedParen = decodeString(parenUnpacked);
String decodedFirst = repeatString(count, decodedParen);
return decodedFirst + decodeString(rest);
} else {
int firstNonLetter = indexOfPred(s, c -> !Character.isLetter(c));
if (firstNonLetter >= 0) {
String allLetters = s.substring(0, firstNonLetter);
String rest = s.substring(firstNonLetter);
return allLetters + decodeString(rest);
} else {
return s;
}
}
}
public static void main(String[] args) {
Solution s = new Solution();
System.out.println(s.decodeString("3[a]2[bc]"));
System.out.println(s.decodeString("3[a2[c]]"));
System.out.println(s.decodeString("2[abc]3[cd]ef"));
System.out.println(s.decodeString("100[leetcode]"));
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment