问题
I'm trying the Morgan and a String challenge in hackerrank (https://www.hackerrank.com/challenges/morgan-and-a-string/)
My attempt is the following:
public static void main(String[] args) {
/* Enter your code here. Read input from STDIN. Print output to STDOUT. Your class should be named Solution. */
Scanner in = new Scanner(System.in);
int testCases = in.nextInt();
for(int i=0; i<testCases; i++){
StringBuilder a = new StringBuilder(in.next());
StringBuilder b = new StringBuilder(in.next());
StringBuilder result = new StringBuilder();
int indexA = 0;
int indexB = 0;
while(indexA < a.length() && indexB < b.length()){
if(a.charAt(indexA)<=b.charAt(indexB)){
result.append(a.charAt(indexA));
indexA++;
}
else{
result.append(b.charAt(indexB));
indexB++;
}
}
if(indexA==a.length()){
result.append(b.substring(indexB,b.length()));
}
else{
result.append(a.substring(indexA,a.length()));
}
System.out.println(result.toString());
}
}
I'm getting the first two cases correctly:
2 JACK DANIEL ABACABA ABACABA
Output:
DAJACKNIEL AABABACABACABA
I'm not quite sure if I am not understanding the problem correctly or maybe I'm getting an overflow with large input cases, I cannot see the other test cases but hope you guys can take a look at the code.
Any help is welcome.
Thanks!
回答1:
I think, the problem occurs when you have the same letter on top of both stacks: you cannot choose arbitrarily (which you do by always choosing the first or a stack), but have to compare the next letters on both stacks (and if they are equal, too, the ones after that and so on), so that you can ensure the optimal continuation...
E.g.
input: bbb bba
your output: bbbbba
correct output: bbabbb
来源:https://stackoverflow.com/questions/33927873/morgan-and-a-string-hackerrank