Valid Panlindrome

초보개발·2023년 8월 25일
0

leetcode

목록 보기
10/39

Valid Panlindrome

https://leetcode.com/problems/valid-palindrome/description/?envType=study-plan-v2&envId=top-interview-150

문제

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 characters include letters and numbers.

Given a string s, return true if it is a palindrome, or false otherwise.

풀이

  1. 회문은 string == string.reverse() 이다.
  2. 회문을 판별하는 boolean 형 메서드를 추가한다.
  3. 허용되는 문자는 알파벳, 숫자이며 알파벳의 경우 대문자는 소문자로 변경한다.
  4. 필터링한 문자열이 회문인지 확인하는 메서드를 호출하고 return

수도 코드

def isPalindrome(s):
	return s == s[::-1]

def sol(s):
	new_s = ""
	for s를 시작부터 끝까지:
    	if 알파벳, 숫자가 아닌 경우:
        	continue
        new_s += c
    
    return isPalindrome(new_s)

Solution(Runtime: 4ms)

import java.util.*;


class Solution {
	// 회문인지 판별하는 메서드
    boolean check(String s) {
        StringBuilder sb = new StringBuilder(s);
        return s.equals(sb.reverse().toString());
    }
	
    public boolean isPalindrome(String s) {
        StringBuilder sb = new StringBuilder();

        for (int i = 0 ; i < s.length(); i++) {
            char c = s.charAt(i);
			
            // 알파벳과 숫자가 아닌 경우 skip
            if (!Character.isLetterOrDigit(c) || c == ' ') {
                continue;
            }
            sb.append(Character.toLowerCase(c)); // 소문자로 변경 
        }
        return check(sb.toString());
    }
}

자바에서 문자열은 주의를 요한다. String은 불변이며 +=로 추가할 때마다 새로운 문자열이 만들어진다. 효율이 매우 좋지 않으므로 StringBuilder를 사용하여 append하는 것이 좋다.
다른 사람들은 정규 표현식을 이용해 replaceAll() 메서드로 한줄로 끝냈다.
s.toLowerCase().replaceAll("\\W+", "");

문자열 문제는 정규 표현식을 알아두면 좋을 것 같다.

0개의 댓글