(알고리즘) codewars : Counting Duplicates

호두파파·2021년 2월 19일
0

알고리즘 연습

목록 보기
3/60
post-thumbnail

문제

Count the number of Duplicates
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

문제 풀이

인수로 주어진 문자열을 배열로 변환하고, 빈 객체를 선언해 배열의 요소들을 객체로 할당할 수 있도록
구현하면 쉽게 햏결할 수 있다.

객체에 프로퍼티가 존재하면 1을 더하고, 존재하지 않는다면 키값을 생성해 값에 1을 할당하는 식으로 빈 객체의 키값과 벨류를 채운다.

이 문제가 요구하는 것은 "중복되는 문자의 갯수"이기 때문에
중복되는 문자를 빈 배열에 넣고, 중복을 제거하는 new Set을 이용했다.

배열의 길이를 반환하면 문제 해결.

function duplicateCount(text){
  let temp = text.toLowerCase().split('').sort( (a, b) => a - b);
  let answer = [];
  const result = {};
  temp.forEach( x => {
    if(result[x]) {
      result[x] += 1;
      unique.push(x);
    } else {
      result[x] = 1;
    }
    if(result[x] > 1) {
      return;
  });
  return answer = [...new Set(unique)].length;
};

다른 문제 풀이

function duplicateCount(text){
  return text.toLowerCase().split('').filter(function(val, i, arr){
    return arr.indexOf(val) !== i && arr.lastIndexOf(val) === i;
  }).length;
}
profile
안녕하세요 주니어 프론트엔드 개발자 양윤성입니다.

0개의 댓글