Skip to content

Instantly share code, notes, and snippets.

@josescalia
Created November 14, 2011 07:47
Show Gist options
  • Save josescalia/1363472 to your computer and use it in GitHub Desktop.
Save josescalia/1363472 to your computer and use it in GitHub Desktop.
Palindrome 1
public class PalindromeChecker {
public static void main(String[] args) {
String sWordToCheck = "malam";
System.out.println("Using palindrome1 : ");
if(isPalindrome1(sWordToCheck))
System.out.println(sWordToCheck + " Is Palindrome ");
else
System.out.println(sWordToCheck + " Is Not Palindrome ");
System.out.println("\n");
System.out.println("Using palindrome2 : ");
if(isPalindrome2(sWordToCheck))
System.out.println(sWordToCheck + " Is Palindrome ");
else
System.out.println(sWordToCheck + " Is Not Palindrome ");
System.out.println("\n");
System.out.println("Using palindrome3 : ");
if(isPalindrome2(sWordToCheck))
System.out.println(sWordToCheck + " Is Palindrome ");
else
System.out.println(sWordToCheck + " Is Not Palindrome ");
}
public static boolean isPalindrome3(String sWordToCheck) {
return sWordToCheck.equals(new StringBuffer(sWordToCheck).reverse().toString());
}
public static boolean isPalindrome1(String word) {
int left = 0; // index of leftmost unchecked char
int right = word.length() - 1; // index of the rightmost
while (left < right) { // continue until they reach center
if (word.charAt(left) != word.charAt(right)) {
return false; // if chars are different, finished
}
left++; // move left index toward the center
right--; // move right index toward the center
}
return true; // if finished, all chars were same
}
public static boolean isPalindrome2(String sWord) {
int len = sWord.length();
for (int i = 0; i < (len % 2); i++) {
if (sWord.charAt(i) != sWord.charAt(len - i - 1)) {
return false;
}
}
return true;
}
}
@iboB
Copy link

iboB commented Nov 14, 2011

bug on line 53: should be len / 2

@josescalia
Copy link
Author

Hi..thanks for review..
but can you please tell me why should be the problem with len % 2 ?

@iboB
Copy link

iboB commented Nov 14, 2011

len%2 is either 0 or 1 (since it's the remainder of n divided by 2)
so, depending on whether len is even, this loop will either make 0 iterations or just 1, and return true on ALL strings of even length (say "bbbaaa") and true on ALL strings of odd length that have the same first and last character (say "maabccm").

look at the head revision of my fork, I added several more test cases and fixed the function

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment