有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

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

Possible Duplicate:
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) 个答案

  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
        }
    }
    
  2. # 2 楼答案

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

    这是不完整的,如果两者都是空的,如果s2是空的呢