Posts Valid Palindrome
Post
Cancel

Valid Palindrome

This question is part of NeetCode150 series.

Problem Description

A phrase is a palindrome if, after converting all uppercase letters into lowercase letters and removing all non-alphanumeric characters, it reads the same forward and backward. Alphanumeric characters include letters and numbers.

Given a string s, return true if it is a palindrome, or false otherwise.

leetcode

Solution

Two Pointer Approach

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
class Solution {
    public boolean isPalindrome(String s) {
        
        s = s.toLowerCase();
        
        int i=0;
        int j=s.length()-1;
        
        while(i<j){
            
            if(!Character.isLetterOrDigit(s.charAt(i))){ i++; continue;}
            if(!Character.isLetterOrDigit(s.charAt(j))){ j--; continue;}
            
            if(s.charAt(i) != s.charAt(j)) return false;
            
            i++; j--;
        }
        
        return true;
        
    }
}
This post is licensed under CC BY 4.0 by the author.