Counting Duplicates ( 6 kyu )

문제

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 (bandB)
"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){
  let obj = {}, count = 0;
  text = text.toLowerCase();
  for ( let i = 0; i < text.length; i++ ) {
    if ( obj[text[i]] ) {
      obj[text[i]]++;
    } else {
      obj[text[i]] = 1;
    }
  }
  for ( let j in obj ) {
    if ( obj[j] > 1 ) count++
  }
  return count;
}

obj에 단어 개수를 담아놓고, 1보다 크면 count를 하나씩 추가해서 리턴

다른 사람의 풀이

function duplicateCount(text){
  return (text.toLowerCase().split('').sort().join('').match(/([^])\1+/g) || []).length;
}

한 줄로 푸는게 역시 제일 멋있어


'자료구조, 알고리즘 > Codewars 문제' 카테고리의 다른 글

Who likes it? ( 6 kyu )  (0) 2017.11.27
Unique In Order ( 6 kyu )  (0) 2017.11.26
Vasya - Clerk ( 6 kyu )  (0) 2017.11.26
Build a pile of Cubes ( 6 kyu )  (0) 2017.11.25
Take a Ten Minute Walk ( 6 kyu )  (0) 2017.11.24

+ Recent posts