写一个递归方法来比较两个字符串?

时间:2012-05-03 17:22:26

标签: java sorting recursion

  

可能重复:
  Using Recursion To Compare Strings To Determine Which Comes First Alphabetically 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));
    }
  }

感谢

2 个答案:

答案 0 :(得分:3)

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

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

答案 1 :(得分:-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
    }
}