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.
Вот задача
Вот моё решение:
function duplicateCount(text){
if(text.length!=0){
var count=0, j,myreg;
text=text.toLowerCase();
for(let i=0;i<text.length;i++){
myreg= new RegExp(text[i],'gi');
if(text.match(myreg).length>=2){
count++;
text = text.replace(myreg,'');
}
}
return count;
}else{
return 0;
}
}
Я понял задачу так: если встречаться символ более одного раза увеличиваем счётчик. В результате вывести счётчик.
Так, для коллекции:
function duplicateCount(text){
let t = text.toLowerCase();
let s = new Set();
let dup = new Set();
for (let c of t) {
if (s.has(c)) dup.add(c);
s.add(c);
}
return dup.size;
}
...
text = text.replace(myreg,'');
i--;
}
...
Тест:
Test.assertEquals(duplicateCount("abbFcccFde"), 3);
Без i--; сначала пропускается первая F при удалении b, а потом - вторая при удалении c.
function duplicateCount(text, expected){
var result = 0;
var counts = {};
var textL = text.toLowerCase();
for(var i = 0; i < textL.length; i++) {
var currentCount = (counts[textL[i]] || 0) + 1;
counts[textL[i]] = currentCount;
if (currentCount == 2)
result++;
}
console.log(`result = ${result}, expected = ${expected}`,
(result == expected)? "passed" : "failed", text);
return result;
}
duplicateCount("", 0);
duplicateCount("abcde", 0);
duplicateCount("aabbcde", 2);
duplicateCount("aabBcde", 2,"should ignore case");
duplicateCount("Indivisibility", 1);
duplicateCount("Indivisibilities", 2, "characters may not be adjacent");
duplicateCount('abcabc', 3);
duplicateCount("abbFcccFde", 3);
duplicateCount('bbb', 1);
Апостиль в Лос-Анджелесе без лишних нервов и бумажной волокиты
Основные этапы разработки сайта для стоматологической клиники
Продвижение своими сайтами как стратегия роста и независимости