Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Largest Substring Between Two Equal Characters in a string in JavaScript
We are required to write a JavaScript function that takes in a string of characters as the only argument.
The function should find that longest string which is sandwiched between two identical characters and return its length.
For example −
If the input string is −
const str = 'sadtrsewak';
Then the output should be −
const output = 6;
because between two 'a' we have the longest desired substring of length 6.
Example
Following is the code −
const str = 'sadtrsewak';
const longestSubstringBetween = (str = '') => {
const map = {};
let res = -1;
for(let i = 0; i < str.length; i++){
const el = str[i];
if(map.hasOwnProperty(str[i])){
res = Math.max(res, i - map[el] - 1);
}else{
map[el] = i;
};
};
return res;
}
console.log(longestSubstringBetween(str));
Output
Following is the console output −
6
Advertisements