问题描述
我正在hackerrank
中尝试Morgan和String的挑战()
I'm trying the Morgan and a String challenge in hackerrank(https://www.hackerrank.com/challenges/morgan-and-a-string/)
我的尝试如下:
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
2JACKDANIELABACABAABACABA
输出:
DAJACKNIEL
AABABACABACABA
DAJACKNIELAABABACABACABA
我不确定我是否不能正确理解问题,或者可能是大型输入案例引起了溢出,我看不到其他测试案例,但希望你们可以看一下代码。
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.
欢迎任何帮助。
谢谢!
推荐答案
我认为,当您在两个堆栈的顶部都具有相同的字母时,就会出现问题:您不能随意选择(总是选择第一个或 a 堆栈来做到),但是必须比较下一个字母在两个堆栈上(如果它们相等,也等于之后的堆栈,依此类推),这样就可以确保最佳的连续性...
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...
Eg
input: bbb bba
your output: bbbbba
correct output: bbabbb
这篇关于摩根和String HackerRank的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!