2012-05-03 73 views
-2

可能重複:
Using Recursion To Compare Strings To Determine Which Comes First Alphabetically Java編寫一個遞歸方法來比較兩個字符串?

我卡在這個遞歸問題按字母順序排序任何兩個字符串。這裏的方法簽名:

int compareTo(String s1, String s2) 

它yeilds:

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

感謝

+0

@AmitBhargava - 我只是說我的代碼,感謝 –

+1

是否與你的代碼有問題嗎?它有什麼問題? –

+0

'compareTo(「」,「Hello World」)的值應該是什麼? – emory

回答

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

這是不完整的,如果兩者都爲空,如果S2是什麼空是什麼?

+0

好點AKJ,是OP需要徹底檢查, – Coffee

+0

好吧,我改變它:'(s1.length()== 0)|| (s2.length()== 0)' –

+3

@IkechukwuOkechukwuJr這仍然不正確。你應該有這樣的條件:if(s1.length()== 0 && s2.length()== 0)return 0; else if(s1.length()== 0 && s2.length()> 0)return -1; else if(s1.length()> 0 && s2.length == 0)return 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 
    } 
} 
+0

只是FYI,而不是's1.substring(1,s1.length())'簡單地寫's1.substring(1)'。這是等同的,更簡單的閱讀。 –

+0

您的for循環是不必要的,因爲它會在第一次使用'return'語句迭代後退出。只需使用's1.charAt(0)'和's2.charAt(0)'並移除for循環。 –

+0

感謝提示@ guillaume-polet – cadizm