본문 바로가기
알고리즘 문제풀이/leetcode

[leetcode 125] Valid Palindrome

by m2162003 2020. 11. 20.

Given a string, determine if it is a palindrome, considering only alphanumeric characters and ignoring cases.

Note: For the purpose of this problem, we define empty string as valid palindrome.

Example 1:

Input: "A man, a plan, a canal: Panama" Output: true

Example 2:

Input: "race a car" Output: false

 

문제 풀이:

난이도 쉬움

 

class Solution {
    public boolean isPalindrome(String s) {
     
        s = s.toLowerCase();
        
        int n = s.length();
        
        int left = 0, right = n-1;
        
        while(left < right){
            
            if(!isValid(s.charAt(left))){
                left++;
            }else if(!isValid(s.charAt(right))){
                right--;
            }else if(s.charAt(left)!=s.charAt(right)){
                return false;
            }else {
                left++;
                right--;
            }
        }
        return true;
    }
    
    private boolean isValid(char c){
        if((c >= 'a' && c <= 'z') || (c>='0' && c<='9')){
            return true;
        }
        
        return false;
    }
}

댓글