[Leetcode] 125. Valid Palindrome

whitehousechef·2025년 5월 20일

https://leetcode.com/problems/valid-palindrome/description/

initial

a pretty easy sol that I dafuq retried many times cuz I tried splitting the string that I built like

    public boolean isPalindrome(String s) {
        StringBuilder sb = new StringBuilder();
        for(char c:s.toCharArray()){
            if((c>='a'&&c<='z') || (c>='A'&&c<='Z')){
                sb.append(Character.toLowerCase(c));
            }
        }
        int length=sb.length()/2;
        int remainder = sb.length()%2;
        System.out.println(length);
        System.out.println(sb.toString());
        for(int i=0;i<length;i++){
            char c = sb.charAt(length - 1 - i);
            if(sb.charAt(i)!=sb.charAt(length-1-i)) return false;
        }
        return true;
    }

But look at sb.charAt(length-1-i). IT looks right but is wrong. Cuz length i declared as half the actual length. So actually Im just comparing half the original string, which is wrong.

Also there can be numbers too so i cant just take characters.

sol

we can use
Character.isLetterOrDigit() to check if is alphabet or num and
Character.toLowerCase()

class Solution {
    public boolean isPalindrome(String s) {
        int left=0;int right=s.length()-1;
        while(left<=right){
            char cl=s.charAt(left);
            char cr=s.charAt(right);
            if(!Character.isLetterOrDigit(cl)) left+=1;
            else if (!Character.isLetterOrDigit(cr)) right-=1;
            else{
                if(Character.toLowerCase(cl)!=Character.toLowerCase(cr)) return false;
                left+=1;
                right-=1;
            }
        }
        return true;
    }
}

complexity

n time
1 space

0개의 댓글