알고리즘 94 - Duplicate Encoder

jabae·2021년 11월 2일
0

알고리즘

목록 보기
94/97

Q.

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"  =>  ")())())"
"(( @"     =>  "))((" 

A)

function duplicateEncode(word){
  let result = "";
  let newWord = word.toLowerCase();
  for (let i = 0; i < newWord.length; i++) {
    if ((newWord.slice(0, i)+newWord.slice(i + 1, newWord.length)).includes(newWord[i]) === true)
      result += ')'
    else
      result += '('
  }
  return result;
}

"(newWord.slice(0, i)+newWord.slice(i + 1, newWord.length)"
.slice()를 이용해서 비교할 요소를 뺀 새로운 단어를 만든 뒤, 검사하는 방식으로 풀었다.

other

.map(요소, 인덱스, 배열) 내장고차함수는 3개까지 인자로 취할 수 있다. 그래서 각 요소를 맵으로 접근해서 배열에 요소의 첫 인덱스(indexOf)와 마지막 인덱스(lastIndexOf)를 비교해서 같으면 유일한 요소이므로 '('를, 다르면 2번 이상 들어있는 것이므로 ')'를 리턴해서 묶어준 것이다.

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

0개의 댓글