【问题标题】:How does recursive isPalindrome function work?递归 isPalindrome 函数如何工作?
【发布时间】:2012-02-24 19:43:01
【问题描述】:

我正在研究一些介绍性的递归问题,我有一个明确的问题想得到解答。我遇到的最烦人的问题是,这个递归如何在下面解决的问题中运行?

尽管已经解决了这个问题,但我只是不明白递归调用是如何进入字符串内部的。只看代码,这个方法似乎只会检查给定字符串两端的两个字符,而不检查其余字符。我的教科书给出了一个非常令人不满意的答案,基本上,只要你的 return 语句改进了问题,就不用担心递归是如何工作的。但是我很难知道如何解决后续的递归问题,而不了解如何以与跟踪循环相同的方式跟踪递归方法。

任何智慧之言将不胜感激。

谢谢!

public class isPalindrome {

public static boolean isPalindrome(String str)
{
    //test for end of recursion
    if(str.length() < 2) {return true;}

    //check first and last character for equality
    if(str.charAt(0) != str.charAt(str.length() - 1)){return false;}

    //recursion call 
    return isPalindrome(str.substring(1, str.length() - 1));
}
public static void main(String[] args)
{
    System.out.print(isPalindrome("deed"));
}
}

【问题讨论】:

    标签: java methods recursion palindrome


    【解决方案1】:

    在 str.substring(1, str.length() -1) 上递归调用 isPalindrome() 函数。因此,对于 isPalindrome() 调用,调用堆栈将如下所示:

    1. isPalindrome("abcddcba"): 
    
       ("a" == "a") = true, so recurse
    
    2. isPalindrome("bcddcb"):
    
       ("b" == "b") = true, so recurse
    
    3. isPalindrome("cddc"):     
    
       ("c" == "c") = true, so recurse
    
    4. isPalindrome("dd"): 
    
       ("d" == "d") = true, so recurse  
    
    6. isPalindrome(""):           
    
       length < 2, so return true
    

    最后一次调用的返回值会一直传播到顶部。

    使用递归,图片总是有帮助的。尽力将调用堆栈绘制成图表。它将允许您可视化并因此更好地理解更复杂的递归。这是一个简单的“线性”递归,但您最终会遇到类似“树”的递归。

    这里有一张图片说明了这个确切的问题,以便您更好地形象化:

    【讨论】:

    • 感谢图表很有帮助,我想我开始掌握这个概念了。
    • 别担心,一旦掌握了这个概念,其他递归算法就更容易理解了=D
    【解决方案2】:

    想想回文:

    risetovotesir
    

    这实际上可以通过从回文 v 开始(一个字符的字符串总是回文,空字符串也是如此)并在前后添加相同的字母来构建:

          v           Start with palindrome 'v'.
         ovo          Add 'o' to both ends.
        tovot         Then 't'.
       etovote        Then 'e'.
      setovotes       Then 's'.
     isetovotesi      Then 'i'.
    risetovotesir     And finally 'r'.
    

    该递归函数使用的过程是相反的方向,将字符串逐位分解。它检测它是否确实是回文,如果两者都是:

    • 第一个和最后一个字符相等;和
    • 字符串的内部(一旦这两个被删除)是回文。

    因此代码可以写成:

    public static boolean isPalindrome (String str) {
        // Zero- or one-character string is a palindrome.
    
        if (str.length() < 2)
            return true;
    
        // If first and last characters are different, it's NOT palindromic.
    
        if (str.charAt (0) != str.charAt (str.length() - 1))
            return false;
    
        // Otherwise it's palindromic only if the inner string is palindromic.
    
        return isPalindrome (str.substring (1, str.length () - 1));
    }
    

    使用peed deep的字符串,不同的级别是:

    1. length 9 >= 2, both ends are 'p', next level checks 'eed dee'.
    2. length 7 >= 2, both ends are 'e', next level checks 'ed de'.
    3. length 5 >= 2, both ends are 'e', next level checks 'd d'.
    4. length 3 >= 2, both ends are 'd', next level checks ' ' (space).
    5. length 1 <  2, return true.
    

    或者,star rots 的非回文(虽然非常接近)给你:

    1. length 9 >= 2, both ends are 's', next level checks 'tar rot'.
    2. length 7 >= 2, both ends are 't', next level checks 'ar ro'.
    3. length 5 >= 2, ends are 'a' and 'o', so return false.
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2011-03-29
      • 1970-01-01
      • 2014-04-25
      • 1970-01-01
      • 1970-01-01
      • 2021-07-22
      • 2019-03-05
      • 2012-02-09
      相关资源
      最近更新 更多