- Data Structure
- Networking
- RDBMS
- Operating System
- Java
- MS Excel
- iOS
- HTML
- CSS
- Android
- Python
- C Programming
- C++
- C#
- MongoDB
- MySQL
- Javascript
- PHP
- Physics
- Chemistry
- Biology
- Mathematics
- English
- Economics
- Psychology
- Social Studies
- Fashion Studies
- Legal Studies
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Finding the power of a string from a string with repeated letters in JavaScript
The power of the 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.
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 < sz; ++i) { let count = 1 while(i < sz && str[i + 1] === str[i] && ++i) power = Math.max(power, ++count) } return power }; console.log(maxPower(str));
Output
And the output in the console will be −
5
Advertisements
To Continue Learning Please Login
Login with Google