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
Longest string with two distinct characters in JavaScript
We are required to write a JavaScript function that takes in a string as the first argument and a number (smaller than the length of string) as the second argument. The function should delete characters from the original string and prepare a new string such that it's the longest string containing at most two distinct characters.
Then at last the function should return the length of that desired string.
For example: If the input string is −
const str = 'kjeljsdl';
Then the output should be −
const output = 4;
because the longest substring with at most 2 distinct characters is 'jljl'
Example
The code for this will be −
const str = 'kjeljsdl';
const longestSubstring = (str = '') => {
const { length } = str;
if (length <= 1){
return 0;
};
const keys = [...new Set(str)];
const arr = [];
let max = 0;
for (let i = 0; i < keys.length - 1; i++) {
for (let j = i + 1; j < keys.length; j++) {
arr.push(keys[i] + keys[j]);
}
}
arr.forEach(item => {
let sub = '';
for (let i = 0; i < str.length; i++) {
if (sub[sub.length - 1] === str[i]) {
sub = '';
break;
}
if (item.includes(str[i])) {
sub += str[i];
}
}
if (sub && sub.length > max){
max = sub.length;
};
});
return max;
}
console.log(longestSubstring(str));
Output
And the output in the console will be −
4
Advertisements