Java solution with 2 pointers. Easy to understand code with comments


  • 0
    S
    public class Solution {
        public boolean isPalindrome(String s) {
            // Empty string is a valid palindrome
            if (s == null || s.length() == 0) return true;
            // Get rid of unneeded symbols
            s = s.replaceAll("[^A-Za-z0-9]","").toLowerCase();
            // Ppointers to the fist and last index
            int lptr = 0, rptr = s.length()-1;
            // While pointers not met each other
            while (lptr <= rptr) 
                // Compare the characters and then shift the pointers
                // Return false if not matching --> Invalid palindrome
                if (s.charAt(lptr++)!= s.charAt(rptr--)) return false;
            return true; 
        }
    }
    

Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.