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

Introduction to JavaScript array deduplication and flattening functions

Table of contents 1. Array flattening (also known...

React-Native environment setup and basic introduction

Environment Preparation 1. Environment Constructi...

Troubleshooting and solutions for MySQL auto-increment ID oversize problem

introduction Xiao A was writing code, and DBA Xia...

Vue computed properties

Table of contents 1. Basic Examples 2. Computed p...

Use HTML to write a simple email template

Today, I want to write about a "low-tech&quo...

Detailed analysis of MySQL master-slave delay phenomenon and principle

1. Phenomenon In the early morning, an index was ...

Detailed explanation of this pointing in JS arrow function

Arrow function is a new feature in ES6. It does n...

Details of MutationObServer monitoring DOM elements in JavaScript

1. Basic Use It can be instantiated through the M...

A brief talk about MySQL semi-synchronous replication

Introduction MySQL achieves high availability of ...

A brief discussion on when MySQL uses internal temporary tables

union execution For ease of analysis, use the fol...

Tutorial diagram of using Jenkins for automated deployment under Windows

Today we will talk about how to use Jenkins+power...

PHP-HTMLhtml important knowledge points notes (must read)

1. Use frameset, frame and iframe to realize mult...

Implementation of mysql data type conversion

1. Problem There is a table as shown below, we ne...

What do CN2, GIA, CIA, BGP and IPLC mean?

What is CN2 line? CN2 stands for China Telecom Ne...