Skip to content

Instantly share code, notes, and snippets.

@kvreem
Last active December 18, 2016 21:17
Show Gist options
  • Save kvreem/bbbf1b7deb60099aa63e66334c164aa8 to your computer and use it in GitHub Desktop.
Save kvreem/bbbf1b7deb60099aa63e66334c164aa8 to your computer and use it in GitHub Desktop.
/**
*
* @author Kareem Khattab
*/
/**
*Given a string, return this output
*“3[a]4[b]” → aaabbbb
*“5[c3[b]]” → cbbbcbbbcbbbcbbbcbbb
*“2[z]3[z2[a]]” → zzzaazaazaa
*/
public class Algorithm1 {
public static void main(String[] args) {
String pattern = "2[3[a]3[b]3[c]]";
System.out.println("Extracting pattern: " + pattern);
System.out.println(getOutput(pattern));
}
private static String getOutput(String pattern) {
int depth = 0;
int start = 0;
int repeat = 0;
char current;
//buffer so I can append my output then use .toString() on the buffer
// Strings are immutable types in Java
StringBuffer output = new StringBuffer();
for (int i = 0; i < pattern.length(); i++) {
current = pattern.charAt(i);
if ('0' <= current && '9' >= current) {
if (depth == 0) {
repeat = repeat * 10 + (current - '0');
}
} else if ('[' == current) {
if (depth == 0) {
start = i + 1;
}
depth += 1;
} else if (']' == current) {
depth -= 1;
if (depth == 0) {
String result = getOutput(pattern.substring(start, i));
for (; repeat > 0; repeat--) {
output.append(result);
}
repeat = 0;
start = 0;
}
} else
if (depth == 0) {
output.append(current);
}
}
return output.toString();
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment