Last active
November 1, 2018 14:08
-
-
Save enesacikoglu/d2c5dd7342ec0f5e3d447a4b68bf6f94 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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