[05.11.22] Coding test

Juyeon.it·2022년 5월 11일
0

Coding test

목록 보기
30/32

Counting Duplicates

Description

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

My answer

function duplicateCount(text){
  let inputArr = text.toLowerCase().split('');
  let resultObj = {};
  
  for(let i = 0; i < inputArr.length; i++) {
    (resultObj.hasOwnProperty(inputArr[i])) ? 
      resultObj[inputArr[i]].count += 1 : resultObj[inputArr[i]] = { count: 1 }
  }
  
  let result = 0;
  
  for(let key in resultObj) {
    if (resultObj[key].count > 1) {
      result += 1;
    }
  }
  
  return result
}

Other solutions

function duplicateCount(text){
  return text.toLowerCase().split('').filter(function(val, i, arr){
    return arr.indexOf(val) !== i && arr.lastIndexOf(val) === i;
  }).length;
}

0개의 댓글

관련 채용 정보