Skip to content

Instantly share code, notes, and snippets.

@yitonghe00
Last active October 25, 2019 21:33
Show Gist options
  • Save yitonghe00/e190808888a09d054c60306b215c7cb3 to your computer and use it in GitHub Desktop.
Save yitonghe00/e190808888a09d054c60306b215c7cb3 to your computer and use it in GitHub Desktop.
125. Valid Palindrome (https://leetcode.com/problems/valid-palindrome/): Given a string, determine if it is a palindrome, considering only alphanumeric characters and ignoring cases. Note: For the purpose of this problem, we define empty string as valid palindrome.
// Two pointer solution
// Time: O(n), 4ms
// Space: O(1), 37.5mb
class Solution {
public boolean isPalindrome(String s) {
int l = 0, r = s.length() - 1;
while(l < r) {
// Ignore non alphanumeric characters
while(l < r && !Character.isLetterOrDigit(s.charAt(l))) {
l++;
}
while(l < r && !Character.isLetterOrDigit(s.charAt(r))) {
r--;
}
if(Character.toLowerCase(s.charAt(l)) != Character.toLowerCase(s.charAt(r))) {
return false;
}
l++;
r--;
}
return true;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment