Skip to content

Instantly share code, notes, and snippets.

@enesacikoglu
Last active November 1, 2018 14:08
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save enesacikoglu/d2c5dd7342ec0f5e3d447a4b68bf6f94 to your computer and use it in GitHub Desktop.
Save enesacikoglu/d2c5dd7342ec0f5e3d447a4b68bf6f94 to your computer and use it in GitHub Desktop.
import java.io.IOException;
import java.util.Stack;
public class Solution {
// Complete the morganAndString function below.
static String morganAndString(String a, String b) {
StringBuilder builder = new StringBuilder();
Stack<String> stackA = new Stack();
Stack<String> stackB = new Stack();
char[] charsA = a.toCharArray();
char[] charsB = b.toCharArray();
for (int i = charsA.length - 1; i >= 0; i--) {
stackA.push(Character.toString(charsA[i]));
}
for (int i = charsB.length - 1; i >= 0; i--) {
stackB.push(Character.toString(charsB[i]));
}
while (!stackA.empty() && !stackB.empty()) {
builder.append(compareAndPopSmallLetter(stackA, stackB));
}
if (stackA.empty()) {
while (!stackB.empty()) {
builder.append(compareAndPopSmallLetter(stackB, stackB));
}
} else if (stackB.empty()) {
while (!stackA.empty()) {
builder.append(compareAndPopSmallLetter(stackA, stackA));
}
}
return builder.toString();
}
private static String compareAndPopSmallLetter(Stack<String> stackA, Stack<String> stackB) {
return stackA.peek().charAt(0) < stackB.peek().charAt(0) ? stackA.pop() : stackB.pop();
}
public static void main(String[] args) throws IOException {
System.out.println(morganAndString("DADBC", "DADB"));
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment