본문 바로가기

컴퓨터/LeetCode

LeetCode 125 valid-palindrome Easy [Java]

문제: https://leetcode.com/problems/valid-palindrome/

 

Valid Palindrome - LeetCode

Can you solve this real interview question? Valid Palindrome - 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 cha

leetcode.com

1. 코드

class Solution {
    public boolean isPalindrome(String s) {
        String str = s.toLowerCase().replaceAll("[^0-9a-z]", "");
        boolean check = true;
        for(int i = 0; i < str.length() / 2; i++) {
            if(str.charAt(i) != str.charAt(str.length() - i - 1)) {
                check = false;
                break;
            }
        }
        return check;
    }
}

2. 설명

정규식을 이용하여 숫자와 영문자만 추출하여 문자열을 저장한 뒤 절반으로 나누어 문자열의 양끝부터 비교하는데 중간에 하나라도 다르면 false를 아니면 true를 반환한다.