繁体   English   中英

Java递归; 我如何简化我拥有的东西?

[英]Java recursion; how can I simplify what I have?

我必须编写以下递归方法:

public static int countA(String s)

但是我发现,如果不声明计数器和位置变量,就不可能做到这一点。 像这样:

public static int countA(String s, int position) {

        int count = 0;

        if( s.charAt(position) == 'A' )
            count++;

        if( position + 1 < s.length() ) {
            count += countA(s, position + 1);
        }

        return count;
    }

如何简化答案,使我的方法与列出的方法相同?

编辑:是的,我想计算字符串中所有的A。

尝试这个:

public static int countA(String s) {
    int count = 0;

    if (s == null)
        return 0;

    if (s.length() == 0)
        return 0;

    if (s.charAt(0) == 'A')
        count++;

    return count + countA(s.substring(1));
}

递归有两种形式:

  • 尾递归:返回值的计算是当前子例程的值和下一个调用的返回值的组合。 例,

     int factorial(int a) { if(a==0) return 1; else return a * factorial( a-1 ); } 
  • 基于累加器的递归:您可以通过添加其他参数来累加结果,并返回累加值。

     int factorial(int a, int fact) { if(a==0) return fact; else return factorial(a-1, a*fact); } 

显然,这里的内容基于累加器,但是您可以将其改进为尾递归。

尾递归被认为更具可读性, 但它可能导致StackOverflow (无双关语)。 这是因为它必须在再次调用子例程之前将当前值推入堆栈。 而且,当您进行大量此类调用时,此堆栈可能会超出其限制。

为了避免此问题,一些编译器将尾递归优化为基于累加器。

关于什么:

public static int countA(String s) {
        if(s==null) return 0;
        if(s.length()==0) return 0;
        if( s.charAt(0) == 'A' )
        {
            return 1 + countA(s.substring(1));
        } else 
        {
            return countA(s.substring(1));
        }
    }

我认为类似这样的方法可以解决问题,这里我们假设countA返回String s中As的数量。

public static int countA(String s)
{
    if(s.length()==0) return 0;  // return 0 if string is empty
    else
    {
        // if the first char is A add 1 to the answer, recurse
        if(s.toCharArray()[0])=='A') return 1+countA(s.subString(1,s.length()));

        // else add nothing to the answer, recurse
        else return countA(s.subString(1,s.length()));
    }
} 

您将position变量从方法中移出并使其countA() static (因为countA()也为static )。

static int position = 0;
public static int countA(String s) {
    int count = 0;
    if( s.charAt(position) == 'A' )
        count++;
    if( position + 1 < s.length() ) {
        position++;
        count += countA(s);
    }
    return count;
}

理想情况下,首先要有终止条件,然后通常通过减少缩进/嵌套来简化代码,并对其执行“不执行任何操作”(通常比绝对需要多进行一次迭代)。

您也不需要局部变量!

public static int countA(String s, int position) {
    if (position == s.length())
        return 0;
    return (s.charAt(position) == 'A' ? 1 : 0) + countA(s, position + 1);
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM