本文介绍了写一个递归方法来比较两个字符串?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
在这个递归问题上,我坚持按字母顺序对任意两个字符串进行排序.这是方法签名:
I'm stuck on this recursion problem to alphabetically sort any two strings. Here's the method signature:
int compareTo(String s1, String s2)
它屈服:
returnval <0
表示s1 < s2
returnval ==0
表示s1 == s2
returnval >0
表示s1 > s2
这是我的代码:
package bonushw;
public class Recursion {
public void main (String[] args){
Recursion recurse = new Recursion();
System.out.println("value is: " + recurse.compareTo("bill","bill"));
}
public int compareTo (String s1, String s2) {
if(s1.length() == 0){
return 0;
}
else if (s1.charAt(0) < s2.charAt(0)){
return -1;
}
else if (s1.charAt(0) > s2.charAt(0)) {
return 1;
}
else {
return compareTo(s1.substring(1), s2.substring(1));
}
}
谢谢
推荐答案
if(s1.length() == 0){
return 0;
}
这是不完整的,如果两个都为空,那么s2为空怎么办?
This is incomplete, what if both are empty, what if s2 is empty?
这篇关于写一个递归方法来比较两个字符串?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!