Clean Java solution beats 97%


  • 1

    Used the char[] to help can speed up the solution

    The code is pretty clear, I used i, j as the start and end pointers.

        public boolean isPalindrome(String s) {
            if (s == null || s.length() < 2) {return true;}
            int i = 0, len = s.length(), count = 0, j = 0;
            
            char[] str = new char[s.length()];
            for (i = 0; i < len; i++) {
                char c = s.charAt(i);
                if ( c >= 'a' && c <= 'z' || c >= '0' && c <= '9') {
                    str[count++] = c;
                }
                else if (c >= 'A' && c <= 'Z') {
                    str[count++] = Character.toLowerCase(c);
                }
            }
            
            i = 0; j = count - 1;
            while (i < j) {
                if (str[i] != str[j]) {return false;}
                i++; j--;
            }
            return true;
        }
    

Log in to reply
 

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