猿问

字符串中的重复元素

我正在尝试编写代码来检测函数中的哪个元素被重复以及重复了多少次。该代码还将忽略大小写的差异。


示例:示例 "abcde" -> 0 # 没有字符重复超过一次 "aabbcde" -> 2 # 'a' and 'b' "aabBcde" -> 2 # 'a' 出现两次, 'b' 出现两次 ( band B) "indivisibility" -> 1 # 'i' 出现六次


这是我的代码:


    //...

    let count = 0;

    for(let i = 0; i < str.length; i++){

      for(let j = 0; j <str.length; j++){

          if(str[i] === str[j]){

            count = count + 1 //Count will tally how many times each given letter is repeated

            return console.log(`${str[i]} occurs ${count}`)

          }

      }

      

    }

  }

  duplicateCount('blaaaab');


尚方宝剑之说
浏览 100回答 3
3回答

杨魅力

循环遍历字符串并存储字符的出现次数function duplicateCount(str) {&nbsp; &nbsp;let result = {}&nbsp; &nbsp;for(let i = 0; i < str.length; i++) {&nbsp; &nbsp; &nbsp; &nbsp;const char = str[i]&nbsp; &nbsp; &nbsp; &nbsp;if(char in result) {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;result[char] +=1&nbsp; &nbsp; &nbsp; &nbsp;} else {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;result[char] = 1&nbsp; &nbsp; &nbsp; &nbsp;}&nbsp; &nbsp;}&nbsp; &nbsp;return result}&nbsp; &nbsp; &nbsp; &nbsp;&nbsp;console.log(duplicateCount('blaaaab'));

动漫人物

您可以Set在此处使用结构并使用 O(n) 获得结果const word = "abcdEedutyhaaaa";const duplicates = Array.from(word.toLowerCase())&nbsp; .reduce((builder, char) => {&nbsp; &nbsp; builder.all.has(char) ? builder.duplicate.add(char) : builder.all.add(char);&nbsp; &nbsp; return builder;&nbsp; }, { duplicate: new Set(), all: new Set() })&nbsp; .duplicate&nbsp; .size;console.log(duplicates); // => 3

慕尼黑8549860

function repeatedCharacters(str){&nbsp; &nbsp;try{&nbsp;return str.toLowerCase().split("").sort().join("").match(/(.)\1+/g).length;&nbsp;}&nbsp;catch(e){&nbsp;return 0;&nbsp;} // if TypeError}console.log(repeatedCharacters("CheeecKKCaaz"))上面的代码告诉了有多少个字符重复,你可以修改它来确定每个字符的出现。
随时随地看视频慕课网APP

相关分类

JavaScript
我要回答