코딩테스트

Valid Palindrome

nayoon 2024. 1. 18. 07:05

Valid Palindrome

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

 

LeetCode - The World's Leading Online Programming Learning Platform

Level up your coding skills and quickly land a job. This is the best place to expand your knowledge and get prepared for your next interview.

leetcode.com

 

풀이 방법

replaceAll을 사용해서 공백, 특수문자 제거 후 대문자로 변환하였다.

 

그리고 앞에서부터 하나씩 비교하는 방법 선택

다 해도 O(n)이고 문자열의 최대 길이가 2 * 10^5 라고 해서 문제없을 거라고 생각해서 풀이 진행하였다.

 

class Solution {
    public boolean isPalindrome(String s) {
        String replacedS = s.replaceAll(" ", "").replaceAll("[^a-zA-Z0-9]", "").toUpperCase();
        boolean result = true;

        int len = replacedS.length();
        if (len == 0) {
            return true;
        }

        for(int i = 0; i < len / 2; i++) {
            if (replacedS.charAt(i) != replacedS.charAt(len - 1 - i)) {
                result = false;
                break;
            }
        }

        return result;
    }
}

 

중간에 한번 틀렸는데 문제에서 alphanumeric character라고 표현하였음에도 문제를 제대로 보지않아서 알파벳만 남기고 전부 제거하였다...

 

문제를 똑바로 읽는 습관도 필요할 것 같다.

 

진행 상황

'코딩테스트' 카테고리의 다른 글

21. Merge Two Sorted Lists  (0) 2024.01.29
235. Lowest Common Ancestor of a Binary Search Tree  (0) 2024.01.28
[leetcode] 46. Permutations  (0) 2023.09.16
[leetcode] 45. Jump Game II  (0) 2023.09.16
[2023-02-28]  (0) 2023.02.28