본문 바로가기

LeetCode/String

[Easy] 125. Valid Palindrome

#문제설명

#문제 풀이

풀이 1.

class Solution {
    public boolean isPalindrome(String s) {
        s = s.toLowerCase().replaceAll("[^a-z0-9]", "");
        int right = s.length() - 1, left = 0;
    
        while(right >= left){
            if(s.charAt(left) != s.charAt(right)){
                return false;
            }
            right--;
            left++;
        }       
        return true;
    }
    
}

풀이 2.

public class Solution {
    public boolean isPalindrome(String s) {
        if (s.isEmpty()) {
        	return true;
        }
        int head = 0, tail = s.length() - 1;
        char cHead, cTail;
        while(head <= tail) {
        	cHead = s.charAt(head);
        	cTail = s.charAt(tail);
        	if (!Character.isLetterOrDigit(cHead)) {
        		head++;
        	} else if(!Character.isLetterOrDigit(cTail)) {
        		tail--;
        	} else {
        		if (Character.toLowerCase(cHead) != Character.toLowerCase(cTail)) {
        			return false;
        		}
        		head++;
        		tail--;
        	}
        }
        
        return true;
    }
}