简体   繁体   中英

How does StringBuilder reverse work in Java?

I am trying to solve this leetcode question https://leetcode.com/problems/palindrome-linked-list/ , but running into trouble with strings and string builders. For some reason, "12".equals"21" -> returns true.

I tried converting from string builder to string, and just using stringbuilder.

class Solution {
public boolean isPalindrome(ListNode head) {
    StringBuilder s = new StringBuilder();
    while (head != null) {
        s.append(head.val);
        head = head.next;
    }
    String a = s.reverse().toString(); 
    String b = s.toString(); 
    return a.equals(b);
}
}

It fails on "12" test case, and returns true.

StringBuilder reverse does not produce a new StringBuilder instance. It causes the underlying characters of the current StringBuilder to be reversed. So,

String a = s.reverse().toString(); 
String b = s.toString();

The second s.toString() is operating on the reversed StringBuilder .

you have to do

String original = s.toString(); 
String reversed = s.reverse().toString();
return original.equals(reversed);

Here's one using only 2 StringBuilders instead of 3 and doesn't use the built-in reversed method. Instead, the while loop traverses through the linked list, appends the current node to the original StringBuilder, and inserts the current node at the front of the reversed StringBuilder. So the built-in insert method helps with reversing the order of the nodes values :

public boolean isPalindrome(ListNode head) {
     StringBuilder original = new StringBuilder(), reversed = new StringBuilder();
     ListNode curr = head;
     while (curr != null) {
         original.append(curr.val);
         reversed.insert(0, curr.val);
         curr = curr.next;
     }
     return original.toString().equals(reversed.toString()) ? true : false;
}

StringBuilder#reverse reverses the character sequence in-place eg

StringBuilder s = new StringBuilder("Hello");
s.reverse();
System.out.println(s); // olleH

To preserve the character sequence in the original instance, you need to clone (create a copy) the original instance and reverse the clone eg

StringBuilder b = new StringBuilder(a).reverse(); // a is the original instance
return a.toString().equals(b.toString());

Note : StringBuilder does not override Object#equals method and therefore even if two StringBuilder instances (say, one and other ) have the same content, one.equals(other) return false . A way to check the equality of the two StringBuilder instances is through their String representation eg one.toString().equals(other.toString()) .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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