Java solution (4-6 ms)


  • 0

    I wanted to try something a bit different. I saw other Posts using Character.isLetterOrDigit so I challenged myself not to use it. Instead I created a filter that will convert UPPERCASE to lowercase and return everything that isn't a alpha numeric as - for consistency. Also if everything else is a '-', when I get to the edge case of empty space between valid characters, it will still pass the test, since '-' == '-'.

    public class Solution {
        public boolean isPalindrome(String s) {
            
            //  If it's empty, its valid
            if (s.isEmpty()) return true;
            
            // Pointers
            int left = 0;
            int right = s.length() - 1;
            
            // Standard while loop
            while (left < right) {
                // Read the left side
                char L = filterRead(s, left);
                // If the left isn't good enough, read some more
                while (left < right) {
                    if (L == '-') {
                        L = filterRead(s, ++left);
                    } else {
                        // Break out, found a valid character
                        break;
                    }
                }
                // Read the right side
                char R = filterRead(s, right);
                // If the right isn't good enough, read some more
                while (left < right) {
                    if (R == '-') {
                        R = filterRead(s, --right);
                    } else {
                        // Break out, found a valid character
                        break;
                    }
                }
                // Simple test
                if (L != R) return false;
                // Advance the pointers
                left++;
                right--;
            }
            
            return true;
        }
        
        public char filterRead(String s, int index) {
            char c = s.charAt(index);
            if (c >= 'A' && c <= 'Z') {
                return (char)(c + (32)); // 'A' is 32 lower then 'a', so just add 32 to convert A to a
            } else if (c >= 'a' && c <= 'z') {
                return c;
            } else if (c >= '0' && c <= '9') {
                return c;
            }
            // Everything else becomes a hyphen for simplisity
            return '-';
        }
    }
    

Log in to reply
 

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