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);
Answer from Thiyagu on Stack OverflowVideos
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;
}
hey guys i need your help in java so i have a very beginner problem and i'll probably be laughed at for asking this but how do you reverse a string in java
so far the online called I've been given to work with is:
import java.util.Scanner;
public class Program
{
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
String text = scanner.nextLine();
char[] arr = text.toCharArray();
//your code goes here
}
}
i don't know how to go about it, all i have to do is reverse the string. uhg it was so easy in python with just the (::-) is that how its written idk it's been some time python.
anyways i would appreciate any help and advice on learning java effectively i don't know much yet, i tried going on leetcode but daaaaamn it was crazy hard, i didn't manage to do any problem. thank you