就快,但你需要修改的情况下在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