-1

可能的重复:
使用递归比较字符串以确定哪个在字母顺序上排在第一位 Java

我被困在这个递归问题上,按字母顺序对任何两个字符串进行排序。这是方法签名:

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));
    }
  }

谢谢

4

2 回答 2

3
if(s1.length() == 0){
      return 0;
    }

这是不完整的,如果两者都为空怎么办,如果s2为空怎么办?

于 2012-05-03T17:30:17.867 回答
-1

尝试这个:

class Compare
{
    public static int compareTo(String s1, String s2)
    {
        int len = s1.length() < s2.length() ? s1.length() : s2.length();

        if (len == 0 && s1.length() > 0)
            return -1;
        else if (len == 0 && s2.length() > 0)
            return 1;

        for (int i = 0; i < len; ++i)
        {
            int v1 = s1.charAt(i);
            int v2 = s2.charAt(i);

            if (v1 == v2)
                return compareTo(s1.substring(1, s1.length()),
                                 s2.substring(1, s2.length()));
            else
                return v1 - v2;
        }

        return 0;
    }

    public static void main(String[] args)
    {
        System.out.println(compareTo("", ""));        //  0
        System.out.println(compareTo("a", "a"));      //  0
        System.out.println(compareTo("ab", "a"));     // -1
        System.out.println(compareTo("a", "ab"));     //  1
        System.out.println(compareTo("abc", "abc"));  //  0
    }
}
于 2012-05-03T17:53:01.093 回答