Skip to content

Instantly share code, notes, and snippets.

@josescalia
Forked from iboB/PalindromeChecker.java
Created November 14, 2011 11:01
Show Gist options
  • Save josescalia/1363727 to your computer and use it in GitHub Desktop.
Save josescalia/1363727 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 halfLen = sWord.length()/2;
for (int i = 0; i < halfLen; i++) {
if (sWord.charAt(i) != sWord.charAt(len - i - 1)) {
return false;
}
}
return true;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment