2015-06-22 122 views
1

我試圖編碼這個,但我沒有得到預期的結果: 給定一個字符串,遞歸計算(無循環)字符串中小寫'x'字符的數量。 countX("xxhixx") → 4 countX("xhixhix") → 3 countX("hi") → 0遞歸遞歸計算特殊字符

這裏是我的方法:

public int countX(String str) { 
    int count = 0; 

    if(str.length() >= 1) { 
     if(str.substring(0, 1).equals("x")) { 
      str = str.substring(1, str.length()); 
      count = count + 1 + countX(str); 
     } 
    } 
    else { 
     str = str.substring(1, str.length()); 
     count = count + countX(str); 
    } 

    return count; 
} 
+0

您的縮進發生了什麼? – khelwood

+0

發佈的代碼甚至沒有編譯。收尾大括號的數量大於開放數量。 –

+0

我在網站上編碼,他們不允許我點擊「標籤」。對於那個很抱歉。 – DigitalMan

回答

1

你有正確的想法,但我認爲你在複雜的事情。只需檢查第一個字符是否爲x(如您所見),並且在這種情況下僅增量count不管它是或沒有,繼續遞歸上:

public static int countX(String str) { 
    int count = 0; 

    if (str.length() > 0) { 
     if (str.substring(0, 1).equals("x")) { 
      ++count; 
     } 

     str = str.substring(1, str.length()); 
     count += countX(str); 

    } 

    return count; 
} 
+0

這個完美的作品。謝謝。對不起,我沒有投票權。 – DigitalMan

+0

@DigitalMan樂意幫忙。請注意,如果這是正確答案,則無論您的聲望如何,您都可以接受它(單擊答案分數下的「檢查」標記)。 – Mureinik

1

假設你有一個字符串 「axbxcx」。下面的代碼僅查看字符串中的第一個字符並確定它是否爲x。如果是這樣,那麼除了字符串其餘部分找到的x的數量之外,還要返回1。如果第一個字符不是x,那麼字符串中x的數量等於不包含第一個字符的字符串中x的數量,這就是返回的結果。

int count(String s) 
{ 
    if (s.length() == 0) // base case 
    { 
     return 0; 
    } 

    if (s.charAt(0) == 'x') 
    { 
     return 1 + count(s.substring(1)); 
    } 
    else 
    { 
     return count(s.substring(1)); 
    } 
} 
0

你應該試試這個(它假設你是初次STR值不爲空,其長度大於0的方法外測試)。

public int countX(String str) { 
     if (str.length() == 1) { 
     return ("x".equalsTo(str) ? 1 : 0); 
     } else { 
     return (str.charAt(0) =='x' ? 1 : 0) + countX(str.substring(1,str.length()) 
     } 

    } 
+0

感謝您的觀察。我糾正它 – iullianr

0

這個怎麼樣?

public static int countX(String str) { 

    if (str.length() == 0) { 
     return 0; 

    } 

    if (str.substring(0, 1).equals("x")) { 
     return 1 + countX(str.substring(1)); 
    }   

    return countX(str.substring(1)); 
} 
0

這是一個簡單的方法來做到這一點。

首先,檢查字符串是否爲空。這是遞歸的終止條件。

然後你的結果僅僅是第一個字符(10)計,添加至計數的字符串的其餘部分(通過調用你的函數上substring(1)計算)。

public static int countX(String str) { 
    if (str.isEmpty()) { 
     return 0; 
    } 
    return (str.charAt(0)=='x' ? 1 : 0) + countX(str.substring(1)); 
}