数据解构和算法

46.字符串中出现最多字符以及出现次数

2022-02-07  本文已影响0人  wo不是黄蓉

day2:js基础->算法。
跟着b站学算法->
实现的几种思路:

/**
 *  使用map方法存储
 *  使用对象键值存储的方法
 *  使用排序+indexof和lastIndexOf方法
 */
function getMaxCount(str) {
  let map = new Map();
  let maxLen = 0,
    maxStr = undefined;
  for (let index = 0; index < str.length; index++) {
    const element = str[index].charCodeAt(0);
    if (!map.has(str[index])) {
      map.set(str[index], 1);
    } else {
      map.set(str[index], map.get(str[index]) + 1);
      if (map.get(str[index]) > maxLen) {
        maxLen = map.get(str[index]);
        maxStr = str[index];
      }
    }
  }
  return "最长字符串为:" + maxStr + ",长度为:" + maxLen;
}
function getMaxCount1(str) {
  let json = {};
  let maxLen = 0,
    maxStr = null;
  for (let index = 0; index < str.length; index++) {
    const element = str[index];
    // console.log(element);
    if (!json[element]) {
      json[element] = 1;
    } else {
      json[element] = json[element] + 1;
      if (json[element] > maxLen) {
        maxLen = json[element];
        maxStr = element;
      }
    }
  }
  // console.log(json);
  return "最长字符串为:" + maxStr + ",长度为:" + maxLen;
}

function getMaxCount2(str) {
  let strArr = [...str].sort();
  // console.log(strArr.sort());
  let maxLen = 0,
    maxStr = null;
  for (let index = 0; index < strArr.length; index++) {
    const element = strArr[index];
    let fIndex = strArr.indexOf(element),
      lastindex = strArr.lastIndexOf(element);
    // console.log(element, fIndex, lastindex, lastindex - fIndex + 1);
    if (lastindex - fIndex + 1 > maxLen) {
      maxLen = lastindex - fIndex + 1;
      maxStr = element;
    }
  }
  return "最长字符串为:" + maxStr + ",长度为:" + maxLen;
}
const str = "hello javascript hello css hello you!";
// console.log(getMaxCount(str));
console.log(getMaxCount1(str));
console.log(getMaxCount2(str));

上一篇 下一篇

猜你喜欢

热点阅读