Skip to content

Instantly share code, notes, and snippets.

@dmnugent80
Last active August 29, 2015 14:15
Show Gist options
  • Save dmnugent80/be0651335c6b8b3644da to your computer and use it in GitHub Desktop.
Save dmnugent80/be0651335c6b8b3644da to your computer and use it in GitHub Desktop.
Is Sentence Palindrome
//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