[codewars] Counting Duplicates

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

알고리즘 연습

목록 보기
16/60
post-thumbnail

Description

Write a function that will return the count of distinct case-insensitive alphabetic characters and numeric digits that occur more than once in the input string. The input string can be assumed to contain only alphabets (both uppercase and lowercase) and numeric digits.

Example

  • "abcde" -> 0 # no characters repeats more than once
  • "aabbcde" -> 2 # 'a' and 'b'
  • "aabBcde" -> 2 # 'a' occurs twice and 'b' twice (b and B)
  • "indivisibility" -> 1 # 'i' occurs six times
  • "Indivisibilities" -> 2 # 'i' occurs seven times and 's' occurs twice
  • "aA11" -> 2 # 'a' and '1'
  • "ABBA" -> 2 # 'A' and 'B' each occur twice

문제 해결

주어진 문자열에서 대소문자 구분없이 중복되고 있다면 중복되고 있는 문자수 만큼을 리턴해야 하는 문제.

이 문제를 해결하기 위해서는 객체를 활용하는 것이 가장 손쉽다.

function duplicateCount(text){
  const textArr = text.toLowerCase().split('');
  const result = {};
  
  textArr.forEach(item => {
    if (result[item]) {
     result[item] = result[item] + 1;
    } else {
     result[item] = 0 + 1;
    }
  });
  let answer = 0; 
  for (let props in result) {
    if (result[props] > 1) {
      answer++;
    }
  }
  return answer;
}

문자열 내에서 대소문자가 구분없이 사용되고 있기 때문에, 소문자로 모두 바꾸어 주었다.
그리고 배열로 바꾸어 forEach 메소드를 통해 요소를 순회하며 빈 객체에 빈도수를 담아주는 작업을 실행했다.
그리고 도출해야 하는 값인 반복해서 사용된 문자의 갯수를 리턴하기 위해 for...in구문을 사용했다.

다른 문제 풀이

function duplicateCount(text){
  var lower = text.toLowerCase();
  var count = 0;
  var used = [];
  
  lower.split('').forEach(function(letter) {
    if (!used.includes(letter) && (lower.split(letter).length - 1) > 1) {
      count++;
      used.push(letter);
    }
  });
  
  return count;
}

includes()
이 메서드는 배열이 특정 요소를 포함하고 있는지 판별합니다.
불리언 값을 리턴한다.

profile
안녕하세요 주니어 프론트엔드 개발자 양윤성입니다.

0개의 댓글