Issue
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.
Solution
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);
Answered By - user7
Answer Checked By - Cary Denson (JavaFixing Admin)