Accepted short one-pass 7ms Java Solution


  • 1
    X

    Idea:
    Keep a front and an end pointer, which will be used to compare characters at those locations.
    Move the front pointer ahead, and end pointer behind till you encounter a valid character (alphanumeric) at each of those positions. If the valid characters do not match, return false. Else keep going.
    Once you are done comparing all and didn't return false, that means your string is a palindrome.

    public class Solution {
        
        public boolean isPalindrome(String s) {
            if(s.length()==0)
                return true;
            char[] array = s.toCharArray();
            int front = 0;
            int end = array.length-1;
            while(front < end) {
                if(!Character.isLetterOrDigit(array[front])) {
                    front++;
                    continue;
                }
                if(!Character.isLetterOrDigit(array[end])) {
                    end--;
                    continue;
                }
                if(Character.toLowerCase(array[front++]) != Character.toLowerCase(array[end--]))
                    return false;
            }
            return true;
        }
    }
    

Log in to reply
 

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