JavaScript递归计算重复字母

时间:2019-01-26 18:34:31

标签: javascript recursion count letter

我在编码时遇到问题。我想计算一个单词中递归重复的字母数。我的代码如下:

var check = words[0]

  if(!words){
     return 0
  } else {
     for(var i = 0; i < words.length; i++){
        if(words[i] == check){
           return 1 //+ countDuplicate (words.slice(1))
        }
     }
     return countDuplicate (words.slice(1))
  }

测试用例的示例:

countDuplicate ('greatestme') // 2, ==> which are 'e' 3 times and 't' 2 times

3 个答案:

答案 0 :(得分:1)

/* Method 1 */
function countDuplicate1(word) {
  var arr = word.split("").reduce((acc, cv) => {
    if(!acc[cv]) {
      acc[cv] = 1;
    } else {
      acc[cv]++;
    }
    return acc;
  }, {});
  return Object.values(arr).filter(val => val >1).length;
}

/* Method 2 */
function countDuplicate2(word) {
  var arr = [];
  for(var i=0; i< word.length; i++) {
    var chr = word[i];
    for(var j=i+1; j< word.length; j++) {
      if((word[j] == chr) && !arr.includes(word[j])) {
        arr.push(word[j]);
      }
    }
  }
  return arr.length;
}
var count1 = countDuplicate1('greatestme');
var count2 = countDuplicate2('greatestme');
console.log(count1);
console.log(count2);

看看是否有帮助。

答案 1 :(得分:1)

const freqDist = ([first, ...rest], counts = {}) => (result => (
  rest.length ? freqDist(rest, result) : result
))({ ...counts, [first]: ((counts[first] || 0) + 1) })

/* More readable alternative with mutable `counts` */
// const freqDist = ([first, ...rest], counts = {}) => {
//   counts[first] = (counts[first] || 0) + 1
//   return (rest.length > 0) ? freqDist(rest, counts) : counts
// }

const stripSingles = obj => Object.keys(obj).reduce((acc, curr) => (
  (obj[curr] > 1) ? { ...acc, [curr]: obj[curr] } : acc
), {})

console.log(stripSingles(freqDist('greatestme')))

答案 2 :(得分:0)

这个问题并不是递归的好选择,但是一种解决方法是维护两个集合:

  • 只出现一次的字符集
  • 多次出现的字符集

在处理下一个字符时,您需要确定如何修改这两个字符集。处理完所有字符后,您将返回第二组字符的大小。

两个集合都被初始化为空集合:

function countDuplicate(word, once = new Set, more = new Set) {
    var check = word[0];
    if (!check) return more.size;
    if (once.delete(check)) { // If successful, it was present
        more.add(check);
    } else {
        once.add(check);
    }
    return countDuplicate(word.slice(1), once, more);
}

const result = countDuplicate ('greatestme');

console.log(result);