input String is Palindrome

What is String?, Declare String Variables, Compare Strings, Concatenate Strings, Read Data and Covert String type data to Integer type and Double Type.
Post Reply
manoj
Posts: 87
Joined: Fri Nov 23, 2018 5:29 am

input String is Palindrome

Post by manoj » Wed Dec 05, 2018 5:29 am

Write a method to check if input String is Palindrome?

swathi
Posts: 134
Joined: Fri Nov 23, 2018 2:52 am

Re: input String is Palindrome

Post by swathi » Wed Dec 05, 2018 5:31 am

A String is said to be Palindrome if it’s value is same when reversed. For example “aba” is a Palindrome String.
String class doesn’t provide any method to reverse the String but StringBuffer and StringBuilder class has reverse method that we can use to check if String is palindrome or not.

private static boolean isPalindrome(String str) {
if (str == null)
return false;
StringBuilder strBuilder = new StringBuilder(str);
strBuilder.reverse();
return strBuilder.toString().equals(str);
}

Sometimes interviewer asks not to use any other class to check this, in that case we can compare characters in the String from both ends to find out if it’s palindrome or not.

private static boolean isPalindromeString(String str) {
if (str == null)
return false;
int length = str.length();
System.out.println(length / 2);
for (int i = 0; i < length / 2; i++) {

if (str.charAt(i) != str.charAt(length - i - 1))
return false;
}
return true;
}

srini
Posts: 85
Joined: Thu Jan 03, 2019 3:58 am

Re: input String is Palindrome

Post by srini » Sat Jan 26, 2019 12:10 pm

To check whether a word is a palindrome I get the char array of the word and compare the chars. I tested it and it seems to work. However I want to know if it is right or if there is something to improve

Example:
========
public class Aufg1 {
public static void main(String[] args) {
String wort = "reliefpfpfeiller";
char[] warray = wort.toCharArray();
System.out.println(istPalindrom(warray));
}

public static boolean istPalindrom(char[] wort){
boolean palindrom = false;
if(wort.length%2 == 0){
for(int i = 0; i < wort.length/2-1; i++){
if(wort != wort[wort.length-i-1]){
return false;
}else{
palindrom = true;
}
}
}else{
for(int i = 0; i < (wort.length-1)/2-1; i++){
if(wort != wort[wort.length-i-1]){
return false;
}else{
palindrom = true;
}
}
}
return palindrom;
}
}

Post Reply

Return to “Java Strings”