美文网首页
找出字符串中出现频率最高的字符

找出字符串中出现频率最高的字符

作者: 苦瓜_6 | 来源:发表于2018-08-15 22:01 被阅读0次

    找出字符串中出现频率最高的字符

    思路 : 函数内新建一个对象,用这个对象来记录每个字符出现的次数,然后再遍历这个对象,找出最多次数

    function maxN(str) {
        let dict = {};
        let count = 0;
        let maxValue;
        for (let i = 0, len = str.length; i < len; i++) {
            if (dict[str[i]]) {
                dict[str[i]] += 1  // 之前出现过,现在每出现一次,次数加 1 
            } else {
                dict[str[i]] = 1   //  第一次出现时,次数记为 1 
            }
        }
        for (key in dict) {
            if (dict[key] > count) {
                maxValue = key
                count = dict[key]
            }
        }
       console.log(dict); //  这个对象里存储了字符串里每个字符串各自出现的次数
      let result  = '出现最多的字符是 '+maxValue + ', 出现次数:'+count ;
       return  result
    };
    maxN('abcdkefgaakkaallkal') // 出现最多的字符是 a 出现次数:6
    

    缺陷: 当出现最多的字符不只一个时,只能找到一个

    maxN('ababababcdff');
    //  {a: 4, b: 4, c: 1, d: 1, f: 2}
    // "出现最多的字符是 a,出现次数:4"
    

    改进一下:

    function maxN(str) {
      let dict = {};
      let count = 0;
      let maxValue;
      for (let i = 0, len = str.length; i < len; i++) {
        if (dict[str[i]]) {
          dict[str[i]] += 1; // 之前出现过,现在每出现一次,次数加 1 
    
        } else {
          dict[str[i]] = 1 //  第一次出现时,次数记为 1 
        }
      }
      for (key in dict) {
        if (dict[key] > count) {
          maxValue = key; // 找出出现次数最多的字符
          count = dict[key]; // 找出最多次数
        }
      }
    
    
      console.log(dict); //  这个对象里存储了字符串里每个字符串各自出现的次数
      let result = [];
      for (key in dict) {
        if (dict[key] === count) {
          let temp = '出现最多的字符是 ' + key + ', 出现次数:' + count;
          result.push(temp)
        }
      }
      return result
    };
    
    //  再来试一试
    maxN('ababababcdff');
    //  {a: 4, b: 4, c: 1, d: 1, f: 2}
    //    ["出现最多的字符是 a, 出现次数:4", "出现最多的字符是 b, 出现次数:4"]
    

    相关文章

      网友评论

          本文标题:找出字符串中出现频率最高的字符

          本文链接:https://www.haomeiwen.com/subject/fopcbftx.html