Skip to content

字符串中出现次数最多的字符 ​

2023-06-16 10:17:39

ts
const str = 'ababajshbaasdaaaa'
// { char:'a', count:9 }

function computeString(str) {
  const compute = {}

  for (let i = 0; i < str.length; i++) {
    let key = str[i]
    if (compute[key]) {
      compute[key] = compute[key] + 1
    } else {
      compute[key] = 1
    }
  }

  let max
  Object.values(compute).forEach(item => {
    if (max) {
      if (max < item) {
        max = item
      }
    } else {
      max = item
    }
  })
  let char
  for (const item in compute) {
    if (compute[item] == max) {
      char = item
    }
  }

  return { char, count: max }
}

console.log(computeString(str))

Released under the MIT License.