본문 바로가기
알고리즘/Codewars

[Codewars] Detect Pangram (6 kyu) / JavaScript

by fluss 2022. 12. 22.

https://www.codewars.com/kata/545cedaa9943f7fe7b000048

 

Codewars - Achieve mastery through coding practice and developer mentorship

A coding practice website for all programming levels – Join a community of over 3 million developers and improve your coding skills in over 55 programming languages!

www.codewars.com

 

DESCRIPTION:

A pangram is a sentence that contains every single letter of the alphabet at least once. For example, the sentence "The quick brown fox jumps over the lazy dog" is a pangram, because it uses the letters A-Z at least once (case is irrelevant).

 

Given a string, detect whether or not it is a pangram. Return True if it is, False if not. Ignore numbers and punctuation.

 

설명:

팬그램은 모든 알파벳 문자를 적어도 한 번 이상 사용한 문장입니다. 예를 들어 "The quick brown fox jumps over the lazy dog"라는 문장은 문자 A-Z를 적어도 한번 이상 사용하기 때문에 팬그램입니다(대소문자는 상관없습니다).

 

문자열이 주어지면 팬그램인지 아닌지를 확인합니다. 맞다면 True 그렇지 않다면 False를 반환합니다. 숫자와 구두점은 무시하세요.

 

풀이

알파벳의 개수인 26개의 크기만 한 배열을 만들고 0으로 초기화를 한다. 주어진 문자열의 모든 문자를 소문자로 바꾸고 그 단어의 아스키코드 값에서 97을 뺀 수를 배열의 인덱스로 해 그 위치를 1로 바꾼다. 그리고 filter로 배열에서 0만 고른 배열을 만들어주고 그 배열의 길이가 0보다 크다면 false를 그렇지 않다면 true를 반환했다.

 

코드

function isPangram(string){
  const letters = string.toLowerCase().split(" ").join('');
  const check = new Array(26).fill(0);
  for(let i = 0; i < letters.length; i++){
    const num = letters.charCodeAt(i) - 97;
    check[num]++;
  }
  const result = check.filter(el => el === 0);
  if(result.length > 0) return false;
  return true;
}

댓글