Skip to content

Instantly share code, notes, and snippets.

@charlespunk
Created August 14, 2013 21:14
Show Gist options
  • Save charlespunk/6235701 to your computer and use it in GitHub Desktop.
Save charlespunk/6235701 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) {
// Start typing your Java solution below
// DO NOT write main() function
if(s == null || s.length() < 1) return true;
s = s.toLowerCase();
int begin = 0;
int end = s.length() - 1;
while(begin < end){
while(begin < s.length() && !isLetter(s.charAt(begin))) begin++;
while(end >= 0 && !isLetter(s.charAt(end))) end--;
if(begin > end) break;
if(s.charAt(begin) != s.charAt(end)) return false;
begin++;
end--;
}
return true;
}
public boolean isLetter(char c){
if(c <= 'z' && c >= 'a') return true;
else if(c <= '9' && c >= '0') return true;
return false;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment