-
Palindrome program
Hi there , I have just written a palindrome program to check if a specific String is or not a palindrome . My program seems fare to complicated for such a simple task. Is there a more conventional way of doing this?
Thankkkkkks Code:
import tcdIO.*;
public class Palyndrome {
public static void main(String args[]) {
String string;
Terminal t = new Terminal();
string = t.readString("Enter the word you want to test\n>");
int counter = string.length() - 1;
int remainder;
int palyndrome = 0;
remainder = string.length() % 2;
for (int i = 0; i < string.length() / 2 + remainder; i++) {
while (counter >= string.length() / 2 + remainder) {
if (string.charAt(i) != string.charAt(counter)) {
palyndrome++;
}
counter--;
}
}
if(palyndrome==0){
t.println(""+string+" is a palyndrome");
}else{
t.println(""+string+" is not a palyndrome");}
}
}
-
I would just have two indexes- start (initialized to zero) and end (initialized to the length of the string minus one). In a loop, check that the char at index start and the char at index end are equal. If they aren't, the String is not a palindrome. Increment start and decrement end before looping again. When start is greater than or equal to end, then the String is a palindrome.
But that's just how I do it by hand or in my head, without any code. If you do it a different way (think about how you decide whether some text is a palindrome or not without any code, just in your head), then that's how your program should work.
-
Would this be cheating? Code:
boolean palindrome = text.equals(new StringBuilder(text).reverse().toString());
-
You could push the string which you're testing onto a stack data structure, char by char, and after its done, pop the stack and form another string with it.
Then compare the two strings.
Read up on Stack datastructure here:
Stack (Java 2 Platform SE 5.0)
(not as nice as dlorde's solution, but at least with this youre doing "work" :D. Actually Im pretty sure the .reverse() method does the same thing as I wrote).
-
Hehe you misspelled Palindrome ;)
Anyway, here's my 4-lines of code to check palindrome:
Code:
public boolean isPalindrome(String s) {
for(int a = 0; a < s.length()/2; a++)
if(s.charAt(a) != s.charAt(s.length()-a-1))
return false;
return true;
}
;)