How to use JavaScript to get the most repeated characters in a string

How to use JavaScript to get the most repeated characters in a string

If you want to keep your technology vibrant, the most effective way is to provide sufficient nutrients through continuous input. We don't have to deliberately pursue advanced or new knowledge points. We can also gain a lot through a comprehensive and multi-dimensional analysis of a basic problem.

topic

Suppose there is such a question: Please get the character with the most repetitions and its repetition times in the string "bianchengsanmei,xuexiyouqudezhishi,jieshiyouqudepengyou,suzaoyouqudelinghun."

Let’s solve this problem today.

analyze

The solution to this type of problem is relatively open, and the implementation methods may be varied. The difference lies in the high or low running performance of the code (different time complexity and space complexity).

There is only one thing to note here: there may be more than one character that meets the maximum number of times.

Objects of use

Solution:

  • Traverse the string, using each character as the key and the number of repetitions as the value, and store them in an object.
  • Traverse the object and get the maximum value.
  • Traverse the object and get the corresponding character key based on the maximum value obtained.
  • Output the result.

The code is implemented as follows:

const testStr = "bianchengsanmei,xuexiyouqudezhishi,jieshiyouqudepengyou,suzaoyouqudelinghun.ii";

// Get the mapping object of each character and its repetition number let wordsObj = {};
for (let index = 0; index < testStr.length; index++) {
    const word = testStr[index];
    word in wordsObj ? wordsObj[word]++ : wordsObj[word] = 1;
}

// Get the maximum number of repetitions let maxNum = 0;
for (const word in wordsObj) {
    const num = wordsObj[word];
    if (num >= maxNum) {
        maxNum = num;
    }
}

// Get the character corresponding to the maximum number of repetitions and output the result for (const word in wordsObj) {
    const num = wordsObj[word];
    if (num === maxNum) {
        console.log(`The character with the most repetitions is: ${ word }, the number of repetitions is: ${ maxNum }`)
    }
}

// The character that appears most often is: i, and the number of times it appears is: 10
// The character that appears most often is: u, and the number of times it appears is: 10

analyze:

  • This should be the solution that many people can think of first, which is in line with the "process-oriented" programming idea.
  • There are three loops in total, and there is a lot of room for optimization.

Arrays & Pointers

Solution:

  • Convert the string into an array and sort it so that repeated characters are grouped together.
  • Use the pointer idea to get the maximum number of repetitions and the corresponding character array.
  • Output the result.

The code is implemented as follows:

const testStr = "bianchengsanmei,xuexiyouqudezhishi,jieshiyouqudepengyou,suzaoyouqudelinghun.ii";

// Convert the string to an array and sort it const testStrArr = testStr.split("").sort();
let startIndex = 0;
let endIndex = 1;
let maxNum = 0;
let validWords = [];

//Use pointer method to obtain the maximum number of repetitions and the character array corresponding to the maximum number while (startIndex < testStrArr.length) {
    // The characters at startIndex and endIndex are different if (testStrArr[startIndex] !== testStrArr[endIndex]) {
        // Calculate the number of characters between startIndex and endIndex const rangeNum = endIndex - startIndex;
        if (rangeNum > maxNum) {
            maxNum = rangeNum;
            // If a new maximum number of times appears, reassign the array storing the qualified characters validWords = [testStrArr[startIndex]];
        } else if (rangeNum === maxNum) {
            // If the new number is equal to the maximum number, push the character into the character array validWords.push(testStrArr[startIndex]);
        }
        startIndex = endIndex;
    }
    endIndex++;
}

// Print results for (let index = 0; index < validWords.length; index++) {
    const word = validWords[index];
    console.log(`The most repeated is: ${ word }, the number of repetitions is: ${ maxNum }`)
}

analyze:

The difficulty and essence of this method lies in the use of pointer method, which allows us to obtain the desired result in one cycle.

Summarize

These are probably the two mainstream ideas for solving problems, and many other solutions can be seen as variations of these two ideas.

No matter how things change, the essence remains the same. As long as you have a clear idea of ​​how to solve the problem, code implementation is just a result. In our daily work and study, we must consciously cultivate our divergent thinking and look at problems from multiple angles. You may discover different scenery!

This is the end of this article on how to use JavaScript to get the most repeated characters in a string. For more relevant JS content on getting the most repeated characters, please search 123WORDPRESS.COM's previous articles or continue to browse the following related articles. I hope everyone will support 123WORDPRESS.COM in the future!

You may also be interested in:
  • How to use regular expressions in JS to remove repeated characters in a string
  • JS method to delete repeated characters in a string
  • Examples of removing consecutive or all repeated characters from a JS string
  • JS method to remove duplicate values ​​in a string
  • How to remove duplicate characters from a JavaScript string
  • JS clears duplicate elements in string array
  • Detailed explanation of how to remove duplicate values ​​in JavaScript arrays and strings
  • JavaScript implements finding the first non-repeating character in a string
  • JS implements a method to find duplicate lines for a sorted string

<<:  Beginners understand MySQL deadlock problem from source code

>>:  Understanding MySQL deadlock routines through unique index S lock and X lock

Recommend

5 ways to achieve the diagonal header effect in the table

Everyone must be familiar with table. We often en...

Detailed explanation of the use of Teleport in Vue3

Table of contents Purpose of Teleport How Telepor...

Steps to deploy hyper-V to achieve desktop virtualization (graphic tutorial)

The hardware requirements for deploying Hyper-V a...

CSS3 gradient background compatibility issues

When we make a gradient background color, we will...

Window.name solves the problem of cross-domain data transmission

<br />Original text: http://research.microso...

Solution to the problem of invalid line-height setting in CSS

About the invalid line-height setting in CSS Let&...

Building an image server with FastDFS under Linux

Table of contents Server Planning 1. Install syst...

How to deploy nodejs service using Dockerfile

Initialize Dockerfile Assuming our project is nam...

Detailed Analysis of Explain Execution Plan in MySQL

Preface How to write efficient SQL statements is ...

How to place large images in a small space on a web page

Original source: www.bamagazine.com There are nar...

jQuery implements dynamic tag event

This article shares the specific code of jQuery t...