/**
* Character methods.
* isLetter(), isDigit(), isLetterOrDigit()
* First check if characters are alphanumberic,
* then check if characters are equal.
*/
public class Solution {
public boolean isPalindrome(String s) {
int low = 0, high = s.length()-1;
while (low < high) {
while (low < high && !Character.isLetterOrDigit(s.charAt(low))) low++;
while (low < high && !Character.isLetterOrDigit(s.charAt(high))) high--;
// the only possibility that two letters are palindrome when they are not equal is lower and upper letters
// therefore, when char is not letter its cannot be palindrome
if (s.charAt(low) != s.charAt(high)) {
if (!Character.isLetter(s.charAt(low)) || !Character.isLetter(s.charAt(high)) || Math.abs(s.charAt(low) - s.charAt(high)) != 32)
return false;
}
low++;
high--;
}
return true;
}
public static boolean isAlphanumeric(char c) {
if (Character.isLetter(c) || Character.isDigit(c)) return true;
return false;
}
}
Leetcode 125. Valid Palindrome
最新推荐文章于 2022-03-21 16:08:25 发布