回文链表使用递归

huangapple 未分类评论60阅读模式
英文:

Palindrome Linkedlist using recursion

问题

索引从0开始。
输入格式:链表元素(用空格分隔,以-1结尾)

某个隐藏的测试用例出现了运行时错误。 main() 函数正在输入并传递 head

public class Solution {
    static String s1 = "", s2 = "";
    public static boolean isPalindrome_2(LinkedListNode<Integer> head) {
        if (head != null) {
            s1 = s1 + head.data;
            isPalindrome_2(head.next);
            s2 = s2 + head.data;
        }
        if (s1.equals(s2))
            return true;
        return false;
    }
}

算法的工作原理:s1 将存储包含所有数据的字符串。 s2 将以相反的方式存储数据,因为它在递归函数之后。然后可以比较这两个字符串。

英文:

Indexing starts from 0.
Input format : Linked list elements (separated by space and terminated by -1)

There is some runtime error on one hidden test case. main() is taking input and passing head.

public class Solution {
    static String s1=&quot;&quot;,s2=&quot;&quot;;
    public static boolean isPalindrome_2(LinkedListNode&lt;Integer&gt; head) {
        if (head != null) {
            s1 = s1 + head.data;
            isPalindrome_2(head.next);
            s2 = s2 + head.data;
        }
        if (s1.equals(s2))
            return true;
        return false;
    }
}

How the algorithm is supposed to work: s1 will store the string containing all data. s2 will store data in reverse manner since it is after recursive function. Then the strings can be compared.

答案1

得分: 0

由于您没有提供可复现的示例,我无法运行您的代码并验证任何假设。因此,以下内容仅基于检查得出。

  1. 如果列表中的数字是 1 和 11,它不是一个回文。然而,您的字符串 s1s2 都应该变为 111,它们是相等的,所以您的方法应该返回 true
  2. 您没有测试末尾的 -1。难道不应该测试吗?

另外,我没有看到任何索引,也没有看到元素之间有任何空格。

我也没有理解运行时错误是如何发生的,抱歉。再次运行您的代码可能会使我有更大的机会理解。

英文:

Since you have not provided a reproducible example, I have not been able to run your code and verify any hypotheses. So this is from inspection alone.

  1. If the numbers in the list ar 1 and 11, it is not a palindrome. Yet your string s1 and s2 should both become 111, that is equal, so your method should return true.
  2. You are not testing for the -1 at the end. Shouldn’t you?

BTW I don’t see any indexing and I don’t see any space between elements.

I also have not understood how a runtime error can occur, sorry. Again, running your code might have given me a greater chance.

huangapple
  • 本文由 发表于 2020年5月3日 16:39:06
  • 转载请务必保留本文链接:https://java.coder-hub.com/61571706.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定