使用递归计算特殊字符



我正在尝试对这个进行编码,但没有得到预期的结果:给定一个字符串,递归地(无循环)计算字符串中小写字母"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;
}

你的想法是对的,但我认为你过于复杂了。只需明确检查第一个字符是否为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;
}

假设您有一个字符串"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));
    }
}

这个怎么样?

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

您应该尝试这样做(它假设您在方法之外进行测试,初始str值不为null并且长度大于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())
      }
   }

这里有一个简单的方法。

首先,检查字符串是否为空。这是递归的终止条件。

然后,结果就是第一个字符(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));
}

你可以试试这个:

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

最新更新