-
-
Save iboB/1363530 to your computer and use it in GitHub Desktop.
Palindrome 1
This file contains 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[] sWordsToCheck = new String[] { | |
"gatemannametag", //p | |
"abcdefghijklmnopqrtuvwxyz", // not p | |
"aaaaa1aaaaa", //p | |
"aaaaa12aaaaa", // not p | |
}; | |
for(int i=0; i<sWordsToCheck.length; ++i) { | |
String sWordToCheck = sWordsToCheck[i]; | |
System.out.print("palindrome1: "); | |
if(isPalindrome1(sWordToCheck)) | |
System.out.println(sWordToCheck + " Is a Palindrome "); | |
else | |
System.out.println(sWordToCheck + " Is Not a Palindrome "); | |
System.out.print("palindrome2: "); | |
if(isPalindrome2(sWordToCheck)) | |
System.out.println(sWordToCheck + " Is a Palindrome "); | |
else | |
System.out.println(sWordToCheck + " Is Not a Palindrome "); | |
System.out.print("palindrome3: "); | |
if(isPalindrome2(sWordToCheck)) | |
System.out.println(sWordToCheck + " Is a Palindrome "); | |
else | |
System.out.println(sWordToCheck + " Is Not a 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(); | |
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