Skip to content

Latest commit

 

History

History
32 lines (30 loc) · 829 Bytes

125. Valid Palindrome.md

File metadata and controls

32 lines (30 loc) · 829 Bytes

Solution1

class Solution {
    public boolean isPalindrome(String s) {
        if (s == null || s.length() == 0) return true;
        s = s.toLowerCase();
        int lo = 0, hi = s.length() - 1;
        while (lo <= hi) {
            Character c1 = s.charAt(lo), c2 = s.charAt(hi);
            if (!Character.isLetterOrDigit(c1)) {
                lo++;
            }
            else if (!Character.isLetterOrDigit(c2)) {
                hi--;
            }
            else {
                if (c1 != c2) {
                    return false;
                } 
                lo++;
                hi--;
            }
        }
        return true;
    }
}

note

  • The idea is to use two pointers to check respective left and right characters. Skip all non-alphanumeric characters.
  • time O(n) space O(1)