Count the most occurring letters in a string

Reprinted from an unknown site that likes JS

let str = "aabbccdd", count the most letters in the string

method one

The key method is the String.prototype.charAt
core concept: first traverse all letters in the string, count the letters and the number of corresponding displays, and finally compare and obtain the letter with the largest number of times.

/**
 * 获取字符串中出现次数最多的字母
 * @param {String} str
 */
function getChar(str) {
    if (typeof str !== 'string') return // 判断参数是否为字符串
    const obj = new Object() // 键为字母,值为次数
    for (let i = 0; i < str.length; i ++) { // 遍历字符串每一个字母
        let char = str.charAt(i) // 当前字母
        obj[char] = obj[char] || 0 // 保证初始值为0
        obj[char] ++ // 次数加1
    }
    let maxChar // 存储字母
    let maxNum = 0 // maxChar字母对应的次数
    for(let key in obj) { // 遍历obj
        if (obj[key] > maxNum) {
            maxChar = key // 比较后存储次数多的字母
            maxNum = obj[key] // 以及它对应的次数
        }
    }
    return maxChar // 返回结果
}

let str = 'aabbbccdd'
console.log('出现次数最多的字母为:' + getChar(str))

Method Two

The key method is the same String.prototype.split
logic and method 1, except that splitthe string is directly split into an array first. It is less efficient than the method.

/**
 * 获取字符串中出现次数最多的字母
 * @param {String} str 
 */
function getChar(str) {
    if (typeof str !== 'string') return // 判断参数是否为字符串
    const obj = new Object() // 键为字母,值为次数
    const arr = str.split('')
    for (let i = 0; i < arr.length; i++) { // 遍历字符串每一个字母
        let char = arr[i] // 当前字母
        obj[char] = obj[char] || 0 // 保证初始值为0
        obj[char]++ // 次数加1
    }
    let maxChar // 存储字母
    let maxNum = 0 // maxChar字母对应的次数
    for (let key in obj) { // 遍历obj
        if (obj[key] > maxNum) {
            maxChar = key // 比较后存储次数多的字母
            maxNum = obj[key] // 以及它对应的次数
        }
    }
    return maxChar // 返回结果
}
let str = 'aabbbccdd'
console.log(getChar(str))

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=325021127&siteId=291194637
Recommended