problem with a palindrome method
Hi i am trying to write a palindrome method but am getting the wrong results
public static boolean isPalindrome(String input){
int b=input.length();
int []array=new int[b];
for(int i=0;i<array.length;i++){
array[i]=Integer.parseInt(input);}
开发者_运维百科
for(int i=0;i<(array.length)/2;i++){
if(!(array[i]==array[array.length-1-i])){
return false;}
}
return true;
}
}
If you put the String into a StringBuilder
you can use the .reverse()
method. then just check if the 2 are equal.
StringBuilder input = new StringBuilder("helloolleh");
StringBuilder value = input.reverse();
if(value.toString().equals(input.toString()){
//process
}
You can go for the simpler method to check for palindrome.
Use the StringBuilder class and use the .reverse()
method to reverse the string and then check for palindrome test.
StringBuilder value1= new StringBuilder("nitin");
StringBuilder value2 = input.reverse();
if(value1.toString().equals(value2.toString()){
System.out.println("This is a palindrome string ..");
}
Or you can go by this way also ..
public static boolean isPalindrome(String word) {
int left = 0;
int right = word.length() -1;
while (left < right) {
if (word.charAt(left) != word.charAt(right)) {
return false;
}
left++;
right--;
}
return true;
}
Not sure why you are using Integer.Parse()
.
Try something like this (mostly following the logic from the question)
public static boolean isPalindrome(String input) {
char[] array = input.toCharArray();
for (int i = 0; i < (array.length) / 2; i++) {
if (!(array[i] == array[array.length - 1 - i])) {
return false;
}
}
return true;
}
You can use two "pointers" one starting from the beginning of the string and one from the end, and move them in opposite directions checking that characters are equals; as soon as you find a difference you know your string is not palindromic; conversely, if you don't find differences you know the string is palindromic:
public static boolean isPalindome(String input) {
char[] cs = input.toCharArray();
for (int i = 0, j = cs.length - 1; i < j; i++, j--) {
if (cs[i] != cs[j])
return false;
}
return true;
}
import java.util.Scanner;
public class Test_String {
private static boolean IsPalindrome(String s)
{
StringBuffer str1 = new StringBuffer(s);
StringBuffer str2 = str1.reverse();
if(s.equalsIgnoreCase(str2.toString()))
return true;
else
return false;
}
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
System.out.println("Enter a String to be checked as Palindrome ");
String in = scan.nextLine();
if(IsPalindrome(in))
System.out.println("\nEntered String is a Palindrome ");
else
System.out.println("\nEntered String is NOT a Palindrome ");
}
}
精彩评论