CodeWars 코딩 문제 2021/01/30 - String array duplicates

이호현·2021년 1월 30일
0

Algorithm

목록 보기
73/138

[문제]

In this Kata, you will be given an array of strings and your task is to remove all consecutive duplicate letters from each string in the array.

For example:

  • dup(["abracadabra","allottee","assessee"]) = ["abracadabra","alote","asese"].

  • dup(["kelless","keenness"]) = ["keles","kenes"].

Strings will be lowercase only, no spaces. See test cases for more examples.

(요약) 같은 문자가 연속되면 하나로 줄여서 return.

[풀이]

function dup(s) {
  return s.map(str => {
    let index = 0;
    let reg = new RegExp(`${str[index]}{2,}`);

    while(str.length > index) {
      if(reg.test(str)) {
        str = str.replace(reg, str[index]);
      }
      else {
        reg = new RegExp(`${str[++index]}{2,}`);
      }
    }

    return str;
  });
};

같은 문자가 연속되는 정규식을 동적으로 만듦.
문자열을 반복하면서 정규식을 이용해서 연속되는 문자는 하나로 바꿈.
그 결과값을 return.
요새 정규식 쓰는 알고리즘 종종 하는데 한 번 제대로 정리해야겠군...

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

0개의 댓글