Last active
August 29, 2015 14:15
-
-
Save dmnugent80/be0651335c6b8b3644da to your computer and use it in GitHub Desktop.
Is Sentence Palindrome
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
//In Place algorithm | |
//A man, a plan, a canal: Panama | |
public class Solution { | |
public static void main(String[] args){ | |
String str = "A,,, man, a;; plan, a c....anal: Panama"; | |
boolean retVal = isPalindrome(str); | |
System.out.println(retVal); | |
} | |
public static boolean isPalindrome(String s) { | |
if (s.length() <= 1) return true; | |
int head = 0; | |
int tail = s.length()-1; | |
while (head < tail){ | |
while (!Character.isLetterOrDigit(s.charAt(head))){ | |
head++; | |
} | |
while (!Character.isLetterOrDigit(s.charAt(tail))){ | |
tail--; | |
} | |
if (Character.toLowerCase(s.charAt(head)) != Character.toLowerCase(s.charAt(tail))){ | |
return false; | |
} | |
head++; | |
tail--; | |
} | |
return true; | |
} | |
} | |
//Alternate, using StringBuffer | |
//A man, a plan, a canal: Panama | |
public class Solution { | |
public boolean isPalindrome(String s) { | |
if (s.length() <= 1) return true; | |
String str = s.replaceAll("[\\W]+", ""); | |
str = str.toLowerCase(); | |
StringBuffer strBuf = new StringBuffer(str); | |
String rev = strBuf.reverse().toString(); | |
return (str.equals(rev)); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment