Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
Finding the power of a string from a string with repeated letters in JavaScript
The power of a string is the maximum length of a non-empty substring that contains only one unique character.
We are required to write a JavaScript function that takes in a string and returns its power.
For example ?
const str = "abbcccddddeeeeedcba"
Then the output should be 5, because the substring "eeeee" is of length 5 with the character 'e' only.
How It Works
The algorithm traverses the string and counts consecutive identical characters. It tracks the maximum count found, which represents the power of the string.
Example
The code for this will be ?
const str = "abbcccddddeeeeedcba"
const maxPower = (str = '') => {
let power = 1
const sz = str.length - 1
for(let i = 0; i
Output
And the output in the console will be ?
5
Alternative Approach
Here's a cleaner implementation that's easier to understand:
const findStringPower = (str) => {
if (!str || str.length === 0) return 0;
let maxPower = 1;
let currentPower = 1;
for (let i = 1; i
5
1
4
0
Conclusion
The power of a string is found by identifying the longest sequence of consecutive identical characters. Both approaches work efficiently with O(n) time complexity, scanning the string once to find the maximum consecutive character count.
