就快,但你需要修改的情況下在str
的第一個字母是不是'x'
。您目前正在做的操作將導致無限遞歸,因爲在str.charAt(0) != 'x'
的情況下,您遞歸地調用str
上的countX
。然而,str
仍然是第一個字母沒有'x'
的字符串,所以它會一次又一次地在str
上調用countX
等。所以解決方法是在str.substring(1)
的第一個字母時僅調用countX
是不是'x'
像這樣,
public int countX(String str) {
if(str.length()==0){
return 0;
}
if(str.charAt(0)=='x'){
return 1 + countX(str.substring(1));
}
else{
return countX(str.substring(1));
}
}
你的方法之前
做比方說,我在"Hello"
叫countX
,這裏的調用堆棧跟蹤會是什麼樣子,
call countX("Hello")
"Hello".length() != 0 so we move on to the next condition
"Hello".charAt(0) != 'x' so we call countX("Hello")
call countX("Hello")
"Hello".length() != 0 so we move on to the next condition
"Hello".charAt(0) != 'x' so we call countX("Hello")
call countX("Hello")
"Hello".length() != 0 so we move on to the next condition
"Hello".charAt(0) != 'x' so we call countX("Hello");
.
.
.
infinite recursion
新的解決方案能做什麼
call countX("Hello")
"Hello".length() != 0 so we move on to the next condition
"Hello".charAt(0) != 'x' so we call countX("ello")
call countX("ello")
"ello".length() != 0 so we move on to the next condition
"ello".charAt(0) != 'x' so we call countX("llo")
call countX("llo")
"llo".length() != 0 so we move on to the next condition
"llo".charAt(0) != 'x' so we call countX("lo");
call countX("lo")
"lo".length() != 0 so we move on to the next condition
"lo".charAt(0) != 'x' so we call countX("o");
call countX("o")
"o".length() != 0 so we move on to the next condition
"o".charAt(0) != 'x' so we call countX("");
call countX("")
"".length() == 0 so return 0
return 0
return 0
return 0
return 0
return 0
請注意,在該解決方案中,我們總能有基本案例(str.length()==0
)的一種方式。而之前會有一些情況(當我們遇到不是x的字母時)會阻止該方法到達基本情況。
嘿艾倫,請檢查[問] - 我們需要看到一些代碼旁邊一個更具體的問題。 – domsson
你到目前爲止嘗試過什麼? –
那麼你的代碼有什麼問題嗎?什麼不行?你有什麼錯誤嗎? – BackSlash