CodeWars 코딩 문제 2021/01/15 - Message Validator

이호현·2021년 1월 15일
0

Algorithm

목록 보기
50/138

[문제]

In this kata, you have an input string and you should check whether it is a valid message. To decide that, you need to split the string by the numbers, and then compare the numbers with the number of characters in the following substring.

For example "3hey5hello2hi" should be split into 3, hey, 5, hello, 2, hi and the function should return true, because "hey" is 3 characters, "hello" is 5, and "hi" is 2; as the numbers and the character counts match, the result is true.

Notes:

  • Messages are composed of only letters and digits
  • Numbers may have multiple digits: e.g. "4code13hellocodewars" is a valid message
  • Every number must match the number of character in the following substring, otherwise the message is invalid: e.g. "hello5" and "2hi2" are invalid
  • If the message is an empty string, you should return true

(요약) 숫자를 기준으로 문자열을 숫자랑 문자로 나눌 때, 숫자와 숫자 뒤에 문자열 길이가 전부 같으면 true, 아니면 falsereturn.

[풀이]

function isAValidMessage(message){
  const reg = /\d+/;
  const splitArr = [];

  while(message.length) {
    const num = reg.test(message) && !message.search(reg) && message.match(reg)[0];
    message = message.replace(num, '');
    const str = reg.test(message) ? message.slice(0, message.search(reg)) : message;
    message = message.replace(str, '');

    splitArr.push(num);
    splitArr.push(str);
  }

  for(let i = 0; i < splitArr.length; i += 2) {
    if(splitArr[i] * 1 !== splitArr[i + 1].length) {
      return false;
    }
  }

  return true;
}

숫자만 뽑을 수 있게 정규식을 하나 만들고, message가 숫자를 포함하면서(reg.test(message)) 첫 번째가 숫자일 경우에(!message.search(reg)) 숫자를 뽑아냄(message.match(reg)).
그리고 뽑아낸 숫자를 문자열에서 replace()로 없앰.
숫자 뒤에 오는 문자열을 구하기 위해 message가 숫자를 포함하고 있으면 바로 slice()를 하고, 아니면 문자열에 숫자가 없으니 그대로 str에 저장.
뽑아낸 숫자랑 문자열을 splitArrpush.
반복문을 이용해서 splitArr에 숫자와 문자열 길이를 계속 비교하다가 다를경우 falsereturn.
반복문이 다 돌아도 이상이 없을 경우는 모든 숫자와 문자열 길이가 같은거니까 truereturn.

profile
평생 개발자로 살고싶습니다

0개의 댓글