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

统计一个字符串出现最多的字母:给出一段英文连续的英文字符窜,找出重复出现次数最多的字母 #35

Open
JCHappytime opened this issue Mar 15, 2021 · 0 comments
Labels

Comments

@JCHappytime
Copy link
Owner

JCHappytime commented Mar 15, 2021

思路

  • 先统计每个字母出现的次数,将其存在一个对象中;
  • 得到的这个对象就是一个以字符名为key,出现次数为value的对象,找到value最大的key并输出就可以了。

实现

var func = function(str) {
  // 统计每个字母出现的次数
  var obj = {};
  for (let i = 0; i < str.length; i++) {
    if (!obj[str.charAt(i)]) {
      obj[str.charAt(i)] = 1
    } else {
      obj[str.charAt(i)] ++;
    }
     // obj 对象的key值是字符名,value是出现次数
    // 找出value最大的key并输出就可以了
    var max = 0, thisChar;
     for (keyValue in obj) {
            if (obj[keyValue] > max) {
                max = obj[keyValue]
                thisChar= keyValue
            }
        }
  return thisChar;
  }
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
Projects
None yet
Development

No branches or pull requests

1 participant