亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

返回輸入中每個字符的遞歸函數

返回輸入中每個字符的遞歸函數

偶然的你 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 關注
  • 167 瀏覽
慕課專欄
更多

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號