我被困在这个递归问题上,按字母顺序对任何两个字符串进行排序。这是方法签名:
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));
}
}
谢谢