Java 用递归计算特殊字符
我正在尝试编写此代码,但没有得到预期的结果: 给定一个字符串,递归(无循环)计算字符串中小写“x”字符的数量。Java 用递归计算特殊字符,java,recursion,counting,Java,Recursion,Counting,我正在尝试编写此代码,但没有得到预期的结果: 给定一个字符串,递归(无循环)计算字符串中小写“x”字符的数量。 countX(“xxhixx”)→ 4. countX(“xhix”)→ 3. countX(“hi”)→ 0 以下是我的方法: public int countX(String str) { int count = 0; if(str.length() >= 1 ) { if(str.substring(0, 1).equals("x")) {
countX(“xxhixx”)→ 4.
countX(“xhix”)→ 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;
}
假设您有一个字符串“axbxcx”。下面的代码只查看字符串中的第一个字符,并确定它是否为x。如果是,那么除了在字符串的其余部分中找到的x的数量之外,还返回1。如果第一个字符不是x,则字符串中的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));
}
}
你的想法是对的,但我认为你把事情复杂化了。只需明确检查第一个字符是否为
x
(如您所知),在这种情况下,仅递增计数无论它是或不是,继续在以下位置递归:
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;
}
您应该尝试这样做(它假设您在方法之外测试初始str值不为null且长度大于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));
}
下面是一个简单的方法
首先,检查字符串是否为空。这是递归的终止条件
然后,您的结果就是第一个字符(1
或0
)的计数,添加到字符串其余部分的计数中(通过调用子字符串(1)
上的函数计算)
你可以试试这个:
public int countX(String str) {
int end = str.length(); //get length of the string
int counter = 0;
if(str.length()==0){
return counter; //recursion will stop here
}else{
if(str.charAt(end-1) == 'x'){
counter++;
}
end--;
str=str.substring(0,end); //your string will perform a decrease in length and the last char will be removed
}
return counter+countX(str);
}
缩进发生了什么?发布的代码甚至无法编译。收尾花括号的数量大于开头花括号的数量。我在一个网站上编码,他们不允许我点击“标签”。很抱歉,这个很好用。谢谢“对不起,我还没有投票权。”DigitalMan很乐意帮忙。请注意,如果这是正确答案,您可以接受它(通过单击答案分数下的“检查”符号),而不管您的声誉如何。
public static int countX(String str) {
if (str.isEmpty()) {
return 0;
}
return (str.charAt(0)=='x' ? 1 : 0) + countX(str.substring(1));
}
public int countX(String str) {
int end = str.length(); //get length of the string
int counter = 0;
if(str.length()==0){
return counter; //recursion will stop here
}else{
if(str.charAt(end-1) == 'x'){
counter++;
}
end--;
str=str.substring(0,end); //your string will perform a decrease in length and the last char will be removed
}
return counter+countX(str);
}