[algorithm] 유효한 팰린드롬

Ho-eng·2023년 4월 25일
0

❓ 유효한 팰린드롬


앞에서 읽을 때나 뒤에서 읽을 때나 같은 문자열을 팰린드롬이라고 합니다.
문자열이 입력되면 해당 문자열이 팰린드롬이면 "YES", 아니면 “NO"를 출력하는 프로그램을 작성하세요.
단 회문을 검사할 때 알파벳만 가지고 회문을 검사하며, 대소문자를 구분하지 않습니다.
알파벳 이외의 문자들의 무시합니다.

  • 입력설명

    첫 줄에 정수 길이 100을 넘지 않는 공백이 없는 문자열이 주어집니다.
  • 출력설명

    첫 번째 줄에 팰린드롬인지의 결과를 YES 또는 NO로 출력합니다.
  • 입력예제 1

    found7, time: study; Yduts; emit, 7Dnuof
  • 출력예제 1

    YES

❗ 문제 풀이

내 풀이

<html>
  <head>
    <meta charset="UTF-8" />
    <title>출력결과</title>
  </head>
  <body>
    <script>
      function solution(str) {
        let answer = "yes"

        let nonReverseStr = str
          .toLowerCase()
          .replace(/[:;,]/g, "")

        let reverseStr = str
          .toLowerCase()
          .replace(/[:;,]/g, "")
          .split("")
          .reverse()
          .join("")

        if (nonReverseStr !== reverseStr) answer = "no"

        return answer
      }
      let str = "found7, time: study; Yduts; emit, 7Dnuof"
      console.log(solution(str))
    </script>
  </body>
</html>
  • 컨셉 및 코드리뷰
    이전의 회문과 같은 케이스.
    문자열 === 거꾸로 뒤집은 문자열 을 비교하는데,
    전체조건은 소문자, : ; , 제거 이고
    문자열을 거꾸로 뒤집기 위해서는 reverse()를 사용해야하는데, 이것은 배열에만 적용되므로 split + join 을 사용했다.
    같다면 yes, 다르다면 no를 뱉는다

정답 소스

<html>
    <head>
        <meta charset="UTF-8">
        <title>출력결과</title>
    </head>
    <body>
        <script>
            function solution(s){
                let answer="YES";
                s=s.toLowerCase().replace(/[^a-z]/g, '');
                if(s.split('').reverse().join('')!==s) return "NO";
                return answer;
            }
            
            let str="found7, time: study; Yduts; emit, 7Dnuof";
            console.log(solution(str));
        </script>
    </body>
</html>
profile
매일 '어제의 나와 오늘의 나는 무엇이 다를까?'를 고민하는 김호엥입니다.

0개의 댓글