-
-
Save josescalia/1363727 to your computer and use it in GitHub Desktop.
Palindrome 1
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment