(알고리즘) CodeWars : Duplicate Encoder

호두파파·2021년 4월 6일
0

알고리즘 연습

목록 보기
11/60
post-thumbnail

Description:

The goal of this exercise is to convert a string to a new string where each character in the new string is "(" if that character appears only once in the original string, or ")" if that character appears more than once in the original string. Ignore capitalization when determining if a character is a duplicate.

Examples

  • "din" => "((("
  • "recede" => "()()()"
  • "Success" => ")())())"
  • "(( @" => "))(("

solution

function solution(s) {
  let answer = '';
  const arr = s.toLowerCase().split('');
  for (let i = 0; i < arr.length; i++) {
    if (arr.indexOf(arr[i]) === arr.lastIndexOf(arr[i])) {
      answer += "(";
    } else {
      answer += ")";
    }
  }
  return answer;
}

map을 이용한 메소드

map은 배열을 순회하며 탐색을 하는데 매우 기능적인 메소드이다.

function duplicateEncode(word){
  return word
    .toLowerCase()
    .split('')
    .map( function (a, i, w) {
      return w.indexOf(a) == w.lastIndexOf(a) ? '(' : ')'
    })
    .join('');
}

reduce를 이용한 메소드

reduce 누산기 함수를 이용해 요소가 중복될때마다 카운트를 해주고 그 정보를 객체에 담았다.
누산기 함수와 맵을 이용해 삼항 연산자를 이용한 풀이. 조금 복잡해 보이지만, 메소드의 원리를 알면 쉽게 이해할 수 있다.

function countCharacters(chars) {
  return chars
    .reduce(function(memo, char) {
      memo[char] = momo[char] ? momo[char] + 1 : 1;
      return memo;
    }, {});
}

function duplicateEncode(word) {
  const chars = word.split('').map(ch => ch.toLowerCase());
  const charsCount = countCharacters(char);
  return char
  	.map(ch => charCount[ch] > 1 ? ')' : '(')
  	.join('');
}
  
profile
안녕하세요 주니어 프론트엔드 개발자 양윤성입니다.

0개의 댓글