StringBuilder reverse does not produce a new StringBuilder instance. It causes the underlying characters of the current StringBuilder to be reversed. So,
Use with AIString a = s.reverse().toString();
String b = s.toString();
The second s.toString() is operating on the reversed StringBuilder.
you have to do
Use with AIString original = s.toString();
String reversed = s.reverse().toString();
return original.equals(reversed);
Answer from Thiyagu on Stack OverflowStringBuilder reverse does not produce a new StringBuilder instance. It causes the underlying characters of the current StringBuilder to be reversed. So,
Use with AIString a = s.reverse().toString();
String b = s.toString();
The second s.toString() is operating on the reversed StringBuilder.
you have to do
Use with AIString 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 :
Use with AIpublic 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;
}
I'm coming from Java, where I'm used to being able to tackle string-reversing problems with something as quick as this:
String palindrome = "level"; StringBuffer buffer = new StringBuffer(palindrome); return buffer.reverse();
I've spent the past few hours studying the documentation of C# and looking for an equivalent, but StringBuilders don't seem to scratch this itch. The most I've found is reversing an array. This seems useful, but since I sometimes like to reverse a string to solve numerical problems (convert an int to a string, reverse the string, return the reversed int), it'd be handy to not have to rely on this.
Since I'm studying the topic, I thought I should at least ask now, am I essentially on the right track? Or is there something obvious that I might be missing?