1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31
| public class ValidPalindrome { public boolean isPalindrome(String s) { if (s == null || s.trim().isEmpty()) { return true; } s = s.trim().toLowerCase(); int i = 0; int j = s.length() - 1; while (i < j) { while (i < s.length() && !isValid(s.charAt(i))) { i++; } while (j >= 0 && !isValid(s.charAt(j))) { j--; } if (i < s.length() && j >= 0 && s.charAt(i) != s.charAt(j)) { return false; } else { i++; j--; } } return true; } private boolean isValid(char c) { boolean isNumber = c >= '0' && c <= '9'; boolean isLetter = c >= 'a' && c <= 'z'; return isNumber || isLetter; } }
|