为了账号安全,请及时绑定邮箱和手机立即绑定

返回输入中每个字符的递归函数

返回输入中每个字符的递归函数

偶然的你 2023-07-14 15:16:13
我正在尝试使用递归来返回字符串中的每个字符。然而,输出不是//We define a function with input parameter.function countCharInString(string) {  //vi Define an empty objec   const result = {};  //we loop through the length of string  for (let i = 0; i < string.length; i++) {     //create another variable for each element in string    const ch = string[i];    //BASE CASE: if string is empty, return Object with nothing     if (!result[ch]) {      return result[ch]=0;    } else {      //RECURSION: 1 plus whatever the length of the substring from the next character onwards is      return countCharInString(result[ch] + 1)    }    }}console.log(countCharInString("Vi skal tælle bogstaver"))输出应如下所示:var result = {l : 3,a : 2,e : 2,s : 2,t : 2,v : 2,b: 1,i : 1,k : 1,o : 1,r : 1,æ : 1};
查看完整描述

2 回答

?
叮当猫咪

TA贡献1776条经验 获得超12个赞

我建议像这样简单地减少


var inputString = 'donald duck';

var result = inputString.split('').reduce((acc, char, index) => {

    if (acc[char] !== undefined) {

      acc[char] = acc[char] + 1;

  }

  else {

    acc = { ...acc, [char]: 1 }

  }

  return acc

}, {})

参见: https: //jsfiddle.net/yswu91zh/21/



查看完整回答
反对 回复 2023-07-14
?
饮歌长啸

TA贡献1951条经验 获得超3个赞

仅递归不会给您所需的输出。递归计算字符后,您必须按频率排序,然后按字符排序。我已经从计数中排除了一堆带空格的标点符号,如果您想排除更多,只需将其添加到标点符号字符串中即可。你必须使用String.prototype.localeCompare()方法来比较字符。此方法比较当前区域设置中的两个字符串。当您使用丹麦语时,您必须将区域设置指定为da。


const punctuations = '.,:;!? ';

const countCharInString = (str, p = {}) => {

  if (str.length === 0) return p;

  const key = str[0].toLowerCase();

  if (!punctuations.includes(key)) {

    if (!p[key]) p[key] = 1;

    else p[key] += 1;

  }

  return countCharInString(str.slice(1), p);

};


const cmp = (x, y) => {

  if (x[1] === y[1]) {

    return x[0].localeCompare(y[0], 'da');

  }

  return x[1] < y[1] ? 1 : -1;

};

const ret = Object.fromEntries(

  Object.entries(countCharInString('Vi skal tælle bogstaver')).sort(cmp)

);

console.log(ret);


查看完整回答
反对 回复 2023-07-14
  • 2 回答
  • 0 关注
  • 82 浏览
慕课专栏
更多

添加回答

举报

0/150
提交
取消
意见反馈 帮助中心 APP下载
官方微信