Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

统计给定字符串中出现次数最多的字符 #6

Open
MY729 opened this issue Jul 19, 2019 · 0 comments
Open

统计给定字符串中出现次数最多的字符 #6

MY729 opened this issue Jul 19, 2019 · 0 comments

Comments

@MY729
Copy link
Owner

MY729 commented Jul 19, 2019

题目

统计给定字符串中出现次数最多的字符

要求:输出字符串中出现次数最多的字符和出现的次数

例如:

传入字符串 "aabbbgggg"

输出

{
    str: "g",
    num: 4
}

解析

  1. 遍历字符串,利用对象属性的唯一性,将每个字符作为对象的属性
  2. 用对象的属性值存储每个字符出现的次数
  3. 找出次数最大的字符并输出

答案

let maxStr = (str) => {
  let obj = {}
  for (let i in str) {
    let char = str[i]
    obj[char] = obj.hasOwnProperty(char) ? obj[char] + 1 : 1
  }
  let char = ''
  let num = 0
  for (let key in obj) {
    if (obj[key] > num) {
      char = key
      num = obj[key] 
    }
  }
  return {
    str: char,
    num: num
  }
}

执行结果:

maxStr('aabbbgggg') // 调用

// 输出
{ str: 'g', num: 4 }
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant