[문자열 탐색][JS] 유효한 팰린드롬

Teasan·2022년 6월 28일
0

Algorythm

목록 보기
5/17
post-thumbnail

유효한 팰린드롬


문제 설명

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

제한 사항

없음

입력 설명

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

출력 설명

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

입출력 예제

▣ 입력예제 1

  • found7, time: study; Yduts; emit, 7Dnuof

▣ 출력예제 1

  • YES

해답/풀이

function solution(s) {
  let answer = "YES";
  let str = s.toLowerCase().replace(/[^a-z]/g, "");
  if (str.split("").reverse().join("") !== str) answer = "NO";

  return answer;
}

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

출력

  • YES

수도 코드

function solution(s) {
  // 0. 반환해야 하는 answer의 초기값은 "YES"로 할당한다.
  let answer = "YES";
  // 1.1 인자로 받아온 문자열을 소문자로 통일시키고,
  // 1.2 인자로 받아온 문자열에서 소문자 알파벳만 남기는 정규식을 사용해서 빈 문자열로 변환해버린다.
  let str = s.toLowerCase().replace(/[^a-z]/g, ""); // foundtimestudyydutsemitdnuof
  // 2. 만약 str을 뒤집은 결과가 str과 같지 않다면 "NO"를 반환하도록 한다.
  if (str.split("").reverse().join("") !== str) answer = "NO";
  // 3. answer의 결과를 최종적으로 반환한다.
  return answer;
}

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

⚡️ Resource


toLowerCase() 메서드

  • toLowerCase() 메서드는 문자열을 소문자로 변환해 반환합니다.

MDN 공식 문서 : String.prototype.toLowerCase()

Example

const sentence = 'The quick brown fox jumps over the lazy dog.';

console.log(sentence.toLowerCase());
// expected output: "the quick brown fox jumps over the lazy dog."

replace() 메서드

  • replace() 메서드는 어떤 패턴에 일치하는 일부 또는 모든 부분이 교체된 새로운 문자열을 반환합니다. 그 패턴은 문자열이나 정규식(RegExp)이 될 수 있으며, 교체 문자열은 문자열이나 모든 매치에 대해서 호출된 함수일 수 있습니다.

Example

const p = 'The quick brown fox jumps over the lazy dog. If the dog reacted, was it really lazy?';

console.log(p.replace('dog', 'monkey'));
// expected output: "The quick brown fox jumps over the lazy monkey. If the dog reacted, was it really lazy?"


const regex = /Dog/i;
console.log(p.replace(regex, 'ferret'));
// expected output: "The quick brown fox jumps over the lazy ferret. If the dog reacted, was it really lazy?"

split() 메서드

  • split() 메서드는 String 객체를 지정한 구분자를 이용하여 여러 개의 문자열로 나눕니다.

MDN 공식 문서 : String.prototype.split()

Example

const chars = str.split('');
console.log(chars[8]);
// expected output: "k"

const strCopy = str.split();
console.log(strCopy);
// expected output: Array ["The quick brown fox jumps over the lazy dog."]

reverse() 메서드

  • reverse() 메서드는 배열의 순서를 반전합니다. 첫 번째 요소는 마지막 요소가 되며 마지막 요소는 첫 번째 요소가 됩니다.

MDN 공식 문서 : Array.prototype.reverse()

Example

const array1 = ['one', 'two', 'three'];
console.log('array1:', array1);
// expected output: "array1:" Array ["one", "two", "three"]

const reversed = array1.reverse();
console.log('reversed:', reversed);
// expected output: "reversed:" Array ["three", "two", "one"]

// Careful: reverse is destructive -- it changes the original array.
console.log('array1:', array1);
// expected output: "array1:" Array ["three", "two", "one"]

join() 메서드

  • join() 메서드는 배열의 모든 요소를 연결해 하나의 문자열로 만듭니다.

MDN 공식 문서 : Array.prototype.join()


⚡️ Reference


✍🏻 자바스크립트 알고리즘 문제풀이 - 인프런

profile
일단 공부가 '적성'에 맞는 개발자. 근성있습니다.

0개의 댓글