Most letters in statistics string

Posted by webbyboy on Sun, 29 Mar 2020 18:15:41 +0200

Reprinted from anonymous station like JS

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

Method 1

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

/**
 * Gets the most frequent letter in the string
 * @param {String} str
 */
function getChar(str) {
    if (typeof str !== 'string') return // Judge whether the parameter is a string
    const obj = new Object() // Key is letter, value is times
    for (let i = 0; i < str.length; i ++) { // Traversing every letter of a string
        let char = str.charAt(i) // Current letter
        obj[char] = obj[char] || 0 // Guaranteed initial value is 0
        obj[char] ++ // Times plus 1
    }
    let maxChar // Storage letter
    let maxNum = 0 // Times corresponding to maxChar letters
    for(let key in obj) { // Traversing obj
        if (obj[key] > maxNum) {
            maxChar = key // More stored letters after comparison
            maxNum = obj[key] // And its corresponding times
        }
    }
    return maxChar // Return result
}

let str = 'aabbbccdd'
console.log('The most frequent letters are:' + getChar(str))

Method two

The key method is String.prototype.split
The logic is the same as method 1, except that the string is directly divided into arrays through split. It's less efficient than the method.

/**
 * Gets the most frequent letter in the string
 * @param {String} str 
 */
function getChar(str) {
    if (typeof str !== 'string') return // Judge whether the parameter is a string
    const obj = new Object() // Key is letter, value is times
    const arr = str.split('')
    for (let i = 0; i < arr.length; i++) { // Traversing every letter of a string
        let char = arr[i] // Current letter
        obj[char] = obj[char] || 0 // Guaranteed initial value is 0
        obj[char]++ // Times plus 1
    }
    let maxChar // Storage letter
    let maxNum = 0 // Times corresponding to maxChar letters
    for (let key in obj) { // Traversing obj
        if (obj[key] > maxNum) {
            maxChar = key // More stored letters after comparison
            maxNum = obj[key] // And its corresponding times
        }
    }
    return maxChar // Return result
}
let str = 'aabbbccdd'
console.log(getChar(str))

Topics: Javascript less