코딩테스트 문제풀이/inflearn

[인프런] Node.js / 섹션3 - 문자열 탐색 / 2. 유효한 팰린드롬

sangchu 2023. 1. 12. 00:35

앞에서 읽을 때나 뒤에서 읽을 때나 같은 문자열을 팰린드롬이라 함

문자열이 입력되면 해당 문자열이 팰린드롬이면 "YES", 아니면 “NO"를 출력

단 회문을 검사할 때 알파벳만 가지고 회문을 검사하며, 대소문자를 구분하지 않음

알파벳 이외의 문자들은 무시

 

나의 풀이

function solution(s) {
  let answer = "YES";
  let string = s.toUpperCase();
  // filter 메서드는 배열에서만 호출 가능
  string = Array.from(string).filter(
    (x) => x.charCodeAt() >= 65 && x.charCodeAt() <= 90
  );
  let length = string.length;
  for (let i = 0; i < Math.floor(length / 2); i++) {
    if (string[i] !== string[length - i - 1]) answer = "NO";
  }
  return answer;
}

let str = "found7, time: study; Yduts; emit, 7Dnuof";
console.log(solution(str));

 

filter 사용하려는데 자꾸 함수가 아니라는것이다

그래서 찾아봤더니 filter는 배열에서만 사용 가능하다고 한다.

문자열도 배열인줄 알았는데 다른가 보다.

그래서 Array.from으로 문자열을 배열로 만들어줬다.

 

TypeError: filter is not a function in JavaScript | bobbyhadz

The "filter is not a function" error occurs when we call the `filter()` method on a value that is not of type array. To solve the error, convert the value to an array before calling the `filter` method or make sure to only call the method on arrays.

bobbyhadz.com

 

강사 풀이

function solution2(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(solution2(str));