【问题标题】:Counting the occurrence of characters of a string, and then substituting them with ( or ) dependant on count logic计算字符串中字符的出现次数,然后根据计数逻辑用 ( 或 ) 替换它们
【发布时间】:2021-08-15 19:03:18
【问题描述】:

我需要将传递给函数的字符串拆分为字符,然后如果该单词中的字符数等于 1,则输出一个(符号,否则)我的第一个 Code Wars 项目。我可以将字符串拆分为字符,但我无法让 push 方法处理新的数组输出,从这里获取 count[str] ? count[str]++ : count[str] = 1; 代码。


  function duplicateEncode(word){ 
    for (i=0; i < word.length; i++){
      var count = 0;
     
      word.split("").forEach(function(str) {    
         count[str] ? count[str]++ : count[str] = 1;
         
         if (count ==1){
            output.push["("];
         } else{
            output.push[")"];
         }
         console.log(output);
      });
    } 
  }

  duplicateEncode("din")
  duplicateEncode("recede")
  duplicateEncode("Success")
  duplicateEncode("(( @")

【问题讨论】:

  • 我不完全理解所需的输出,您能否添加更多说明。
  • 对不起,基本上如果我们以第一个字符串“din”为例,我们将其传递给duplicateEncode函数,该函数需要计算该字符串中每个字符的出现次数,如果它等于1,那么我们输出(否则)所以“din”字符串的最终输出将是)))因为每个字符在字符串中只出现一次,我试图分割字符串并计算字符,但我正在努力创建一个输出数组我可以在末尾调用将包含 ))) 字符作为输出到控制台的示例。亲切的问候乔恩

标签: javascript arrays string


【解决方案1】:

先统计每个字符的出现次数,然后再映射到单词上进行比较 OccuranceCount 并用编码字符替换

function duplicateEncode(word){
  characterOccurance = {} // will be {"char": "number of occurance"}

  word.split('').forEach(char => {
     if(characterOccurance[char]){ // if exist 
       characterOccurance[char] += 1; // increase the occurance count
     }else{
       characterOccurance[char] = 1;// set occurance to one
     }
  })

  let output = word.split('').map(
                    char => characterOccurance[char] == 1 ? ')' :'(' 
                    ).join('');
  return output;

}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2014-04-24
    • 2020-05-06
    • 2020-02-21
    • 2012-02-12
    • 2012-06-24
    相关资源
    最近更新 更多