125.Valid Palindrome

Yunes·2022년 5월 28일
0
post-thumbnail

#1. Valid Palindrome

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

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

Example 1:

Input: s = "A man, a plan, a canal: Panama"
Output: true
Explanation: "amanaplanacanalpanama" is a palindrome.

Example 2:

Input: s = "race a car"
Output: false
Explanation: "raceacar" is not a palindrome.

Example 3:

Input: s = " "
Output: true
Explanation: s is an empty string "" after removing non-alphanumeric characters.
Since an empty string reads the same forward and backward, it is a palindrome.

Constraints:

  • 1 <= s.length <= 2 * 105
  • s consists only of printable ASCII characters.

팰린드롬

앞뒤가 똑같은 단어인지 확인하라는 문제

이전에 파이썬 학습을 하며 이 문제를 본 적이 있기에 어떻게 푸는지를 알고 있는 상태에서 Golang 을 사용한 코드는 어떻게 짤 수 있을까 하며 시작했다.

처음엔 인덱스로 접근했다. 문자열 각 글자마다 읽어가며 문자열의 길이를 구하고 첫 인덱스와 마지막 인덱스의 글자를 비교하며 같은지 여부를 구했었다. 당연하게도 코드 길이도 길어지고 인덱스 접근을 잘못하면 PANIC (golang 에서의 에러처리)이 뜬다.

파이썬처럼 sampleArray[::-1] 로 순서를 뒤집는 기능이 있었다면 참 좋았을텐데 고랭엔 그런 기능은 없었다.(있을수도 있는데 아직은 모르겠다.)

권장되는 아이디어는 다음과 같다.
우선 문자열을 뒤집고 처음 문자열과 비교해서 같은지 여부를 판단해서 팰린드롬을 구하는 것이다.


나의답

func isPalindrome(s string) bool {
    if len(s) == 0{
        return true
    }
    reg := regexp.MustCompile("[^a-zA-Z0-9]+/g")
    converted_string := reg.ReplaceAllString(strings.ToLower(s), "")
    compare := ""
    for _, v := range converted_string {
        compare = string(v) + compare
    }
    if compare == converted_string {
        return true
    } else {
        return false
    }
}

해석

regexp.MustComile : 정규 표현식. a-z, A-Z, 0-9 이 아니라면(^)
reg.ReplaceAllString(aString, bString) : aString 을 bString 으로 바꾸어라
strings.ToLower(s) : s 라는 문자열을 소문자로 바꾸어라(Ban -> ban, I am developer. -> i am developer.)
=> 여기까지 주어진 문자열에서 대문자를 소문자로 바꾸고 그 외에 특수문자는 공백으로 바꾸는 처리를 했습니다.

이후 소문자로 바꾸고 특수문자를 제거한 converted_string 문자열을 반복문으로 처음부터 읽어와서 순서를 바꿔줬습니다. (Abc. -> abc -> a, b, c 순서로 읽어서 a -> ba -> cba 이렇게 재배치했습니다. )

이후 마지막으로 이렇게 앞뒤를 뒤집은 문자열이 converted_string 과 같은지 비교해서 앞뒤를 뒤집었는데도 동일하면 팰린드롬이고 아니면 false 를 반환했습니다.

평가


Runtime: 234 ms, faster than 8.83% of Go online submissions for Valid Palindrome.
Memory Usage: 8.8 MB, less than 9.84% of Go online submissions for Valid Palindrome.

profile
미래의 나를 만들어나가는 한 개발자의 블로그입니다.

0개의 댓글