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 Substring with At Most K Distinct Characters in C++
Suppose we have a string; we have to calculate the length of the longest substring T that contains at most k distinct characters.
So, if the input is like s = "eceba", k = 2, then the output will be 3 as T is "ece" which its length is 3.
To solve this, we will follow these steps −
ans := 0
Define one map m
n := size of s
x := 0
-
for initialize j := 0, i := 0, when j < n, update (increase j by 1), do −
(increase m[s[j]] by 1)
-
if m[s[j]] is same as 1, then −
(increase x by 1)
-
while (x > k and i <= j), do −
(decrease m[s[i]] by 1)
-
if m[s[i]] is same as 0, then −
(decrease x by 1)
(increase i by 1)
ans := maximum of ans and (j - i + 1)
return ans
Example
Let us see the following implementation to get better understanding −
#include <bits/stdc++.h>
using namespace std;
class Solution {
public:
int lengthOfLongestSubstringKDistinct(string s, int k) {
int ans = 0;
unordered_map<char, int> m;
int n = s.size();
int x = 0;
for (int j = 0, i = 0; j < n; j++) {
m[s[j]]++;
if (m[s[j]] == 1)
x++;
while (x > k && i <= j) {
m[s[i]]--;
if (m[s[i]] == 0)
x--;
i++;
}
ans = max(ans, j - i + 1);
}
return ans;
}
};
main() {
Solution ob;
cout << (ob.lengthOfLongestSubstringKDistinct("eceba", 2));
}
Input
"eceba", 2
Output
3
Advertisements