检测回文链表,将其转换为字符串。

huangapple go评论73阅读模式
英文:

Detecting a palindrome linked list by converting it into a String

问题

以下是翻译好的代码部分:

public static boolean isPalindromeString(String s) {
    int n = s.length();

    for (int i = 0; i < (n/2); i++) {
        if (s.charAt(i) != s.charAt(n - i - 1))
            return false;
    }

    return true;
}

public static boolean isPalindrome(LinkedListNode<Integer> head) {    
    if(head == null)
        return true; //当链表为空时,它是一个回文

    StringBuilder s = new StringBuilder();

    while(head != null){
        s.append(head.data);
        head = head.next;
    }

    // System.out.println("链表转换为字符串: " + s.toString());

    return isPalindromeString(s.toString());
}
英文:

I am supposed to check if a linked list is a palindrome or not, so I traversed through the LL and converted all the elements into a String, then passed the String to a function which determines if it's a palindrome or not.

Is this approach correct? Is it suitable to use this approach during interviews and tests?

The method I found online reversed the LL and then compared all the values one by one, but honestly it seemed my method was simpler. Here is my code snippet:

public static boolean isPalindromeString(String s) {
    int n = s.length();

    for (int i = 0; i &lt; (n/2); i++) {
        if (s.charAt(i) != s.charAt(n - i - 1))
            return false;
    }

    return true;
}

public static boolean isPalindrome(LinkedListNode&lt;Integer&gt; head) {    
    if(head == null)
        return true; //when list is empty, it is a palindrome
    
    StringBuilder s = new StringBuilder();
    
    while(head != null){
        s.append(head.data);
        head = head.next;
    }

    // System.out.println(&quot;LL as string: &quot; + s.toString());

    return isPalindromeString(s.toString());
}

答案1

得分: 1

尝试添加几行代码,例如在第三行添加以下内容:

int itr = n-1;

现在用以下内容替换这一行:

if (s.charAt(i) != s.charAt(n - i - 1))

改为:

if (s.charAt(i) != s.charAt(itr))

并且在 for 循环中 if 语句结束后添加以下行:

itr--;
英文:

Try to add a few lines of code such as
on the third line add this:

int itr = n-1;

now replace this:

if (s.charAt(i) != s.charAt(n - i - 1))

with:

if (s.charAt(i) != s.charAt(itr))

and at the end add the below line after the ending of if statement with in for loop:

itr--;

答案2

得分: 0

这取决于你如何定义回文。

  • 这个列表是回文吗?[1, 2, 3, 321]
  • [10, 20, 10] 呢?
  • 或者 [-5, -5] 呢?

如果答案分别是 '是'、'否' 和 '否',那么你的代码完成了任务,否则它不会。

此外,如果你得到的 linkedlistnode(它不是标准的 Java,可能是你的作业练习的一部分)是所谓的双向链表(这意味着:你可以像正向迭代一样轻松地逆向迭代它,而且有一种快速轻松地获取最后一个元素的方法),那么有一种更有效的方法可以做到这一点。如果不是,这种方法就可以。

英文:

Depends on how you define palindrome here.

  • Is this list a palindrome? [1, 2, 3, 321]?
  • How about [10, 20, 10]?
  • Or what about [-5, -5]?

If the answers are respectively 'yes', 'no', and 'no', then your code does the job, otherwise it won't.

Furthermore, if that linkedlistnode you're getting (it's not standard java, must be part of your homework exercise) is a so-called doubly linked list (which means: You can iterate through it backwards just as well as forwards, and there is a way to get the last element quickly and easily), then there is a much more efficient way to do this. If not, this approach is fine.

答案3

得分: 0

你的方法虽然简单,但占用更多内存和处理器资源。

链表的优点在于处理大量元素时的内存效率。链表的每个节点对象单独存储在堆内存中。这消除了为大型列表分配巨大连续空间的需要。这导致了内存效率的提高,但会增加额外的时间复杂度。反转链表也更加容易。你只需要将“下一个”节点替换为适当的节点。通常,Java链表有一个“last”参数,这使得反转变得更简单。(最坏情况下,单向链表的时间复杂度可能为O(n**2),双向链表的时间复杂度为O(n))

当你将每个元素添加到StringBuilder对象中,然后将其转换为单个字符串,最终的字符串占用了连续的内存块。如果结果字符串非常大,则内存开销也会更高。此外,String对象还有一些链表没有的其他开销。(在这里查阅更多信息:https://www.javamex.com/tutorials/memory/string_memory_usage.shtml)

因此,尽管你的算法能够工作,但在处理大型列表时可能效率不高。

英文:

Your method is simple, yet more memory and processor taxing.

The beauty of linked list lies in its memory efficiency when handling large number of elements. Each Node object of a linked list is stored on the heap memory separately. This eliminates the need for allocating huge contiguous space for large lists. This results in memory efficient, but additional time complexity. Reversing linked list is also much easier. You just have to replace the next node with proper one. Often java linked lists have a last parameter which makes it easier to reverse. (Worst case singly linked list might take O(n**2) and Double linked list takes O(n) time)

When you add each element to StringBuilder object and the converting it to a single string, the final string takes up a contiguous block of memory. If the resulting string is very large, the toll on memory would also be higher. Plus, String object has some other overheads which linked list doesn't have. (Check this for more info: https://www.javamex.com/tutorials/memory/string_memory_usage.shtml)

So, although your algorithm works, it might be inefficient when handling large lists.

huangapple
  • 本文由 发表于 2020年9月6日 13:07:08
  • 转载请务必保留本文链接:https://go.coder-hub.com/63760892.html
匿名

发表评论

匿名网友

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

确定