计算传入字符串中的重复项

问题描述 投票:0回答:5

所以我在 codewars 上遇到了这个问题,我必须在传入的字符串中找到相同的字母,并返回该字符串中出现两次或两次以上的字母。这是我的尝试,抛出了一个错误:

function duplicateCount(text){
  text.split('')
  for(var i = 0, i < text.length, i++) {
    for(var j = 1, j < text.length + 1, j++)
      if(text[j] = text[i]) {
        return text[i]
      }
    else return
  }
  //...
}

我的经验很少,所以不要太苛刻lmao

javascript
5个回答
1
投票

您可以尝试将字符串数组转换为集合。由于集合不能有重复项,因此您将得到大小差异。因此,计数。

const countDuplicates = (str) => {
    const arr = str.split(''); 
    const arrSet = new Set(arr);
    return arr.length - arrSet.size 
}

console.log(countDuplicates('abcdac')

输出:2

编辑:我错过了您询问返回重复字符的部分。为此:

const getDuplicateChars = (str) => { 

const arr = str.split('');
const duplicateChars = [];
const sortedArr = [...arr].sort();

sortedArr.forEach((elem, index) => {
    if(sortedArr[index+1] === elem) {
        duplicateChars.push(elem);
    }
});
return duplicateChars;
}

let duplicateChars = getDuplicateChars('abcdac');

0
投票

这里有两种方法可以确定字符串中的哪些字符在该字符串中出现两次或多次。

了解更多:

const str = "I_am_a_string_with_probably_duplicate_characters";
console.log(JSON.stringify(duplicateCount(str)));
console.log(duplicateCountLoop(str).join("; "));

// using a reducer/filter
function duplicateCount(text){
  // determine the frequencies of each character in the string
  const charFrequencies = text.split('')
    .reduce( (acc, chr) => ({...acc, [chr]: (acc[chr] || 0) + 1}), {});
  // filter the result for character with more than 1 ocurrences  
  return Object.fromEntries(Object.entries(charFrequencies)
    .filter( ([key, value]) => value > 1 )
  );
}

// in a loop
function duplicateCountLoop(text){
  // determine the frequencies of each character in the string
  const textIterable = text.split('');
  let characterFrequencies = {};
  for (let chr of textIterable) {
    characterFrequencies[chr] = (characterFrequencies[chr] || 0) + 1;
  }
  let result = [];
  for (freq in characterFrequencies) {
    if (characterFrequencies[freq] > 1) {
      result.push(`${freq}: ${characterFrequencies[freq]}`);
    }
  }
  return result;
}


0
投票

与标题不同,您的问题正文和代码表示您希望字母出现多次。

您的方法有一些问题。

text.split('')
不会改变原始数组。它只是返回一个数组。

;
循环中使用
,
代替
for

这是 ES6 中的另一种方法。

  1. 将字符串转换为小写以匹配所有字符,无论大小写。如果您想匹配大小写,请删除
    .toLowerCase()
  2. 将字符串拆分为数组
  3. 使用带有条件
    (x,y) => str.indexOf(x) != y)
    的过滤器来获取重复元素。
  4. 由于结果数组可能有重复元素,而您只需要重复元素,因此我们需要从数组中删除重复元素。
  5. 使用带有
    conditition (x,y) => arr.indexOf(x) == y)
    的过滤器来获取不重复的元素。
  6. 这里,我使用 IIFE 将第一个过滤数组传递给第二个过滤函数并直接返回。
  7. 如果需要,您可以使用
    Set
    代替第二个过滤器。

duplicateFind = (str) => {
  str = str.toLowerCase().split('');
  return ((arr) => arr.filter((x, y) => arr.indexOf(x) == y))(str.filter((x, y) => str.indexOf(x) != y))
}
console.log("Letters appearing more than once in string 'Hello there'");
console.log(duplicateFind("Hello there"));


0
投票

你可以试试这个:

let duplicate=text.split('').filter((item, index) => text.split('').indexOf(item) != index)

0
投票

const value = 'blockquotes';
let arr = value.split('');
let res = {};
for(let i = 0; i < arr.length ; i++){
if(Object.keys(res).includes(arr[i])){
res[arr[i]] = res[arr[i]]+1;
}
else{
res[arr[i]] = 1;
}
}
console.log(res);

© www.soinside.com 2019 - 2024. All rights reserved.