Skip to content

Instantly share code, notes, and snippets.

@charlespunk
Last active December 12, 2015 02:38
Show Gist options
  • Save charlespunk/4700456 to your computer and use it in GitHub Desktop.
Save charlespunk/4700456 to your computer and use it in GitHub Desktop.
Given a string, determine if it is a palindrome, considering only alphanumeric characters and ignoring cases.
For example,
"A man, a plan, a canal: Panama" is a palindrome.
"race a car" is not a palindrome.
Note:
Have you consider that the string might be empty? This is a good question to ask during an interview.
For the purpose of this problem, we define empty string as valid palindrome.
public class Solution {
public boolean isPalindrome(String s) {
if(s == null) return false;
if(s.equals("")) return true;
s = s.toLowerCase();
int f = -1;
int e = s.length();
boolean is = true;
while(f < e){
while(!Character.isLetter(s.charAt(++f)) && !Character.isDigit(s.charAt(f)) && f < s.length() - 1);
while(!Character.isLetter(s.charAt(--e)) && !Character.isDigit(s.charAt(e)) && e > 0);
if(!Character.isLetter(s.charAt(e)) && !Character.isDigit(s.charAt(e))
&& !Character.isLetter(s.charAt(f)) && !Character.isDigit(s.charAt(f))) break;
else if(s.charAt(f) != s.charAt(e)){
is = false;
break;
}
}
return is;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment