
- C++ Basics
- C++ Home
- C++ Overview
- C++ Environment Setup
- C++ Basic Syntax
- C++ Comments
- C++ Data Types
- C++ Variable Types
- C++ Variable Scope
- C++ Constants/Literals
- C++ Modifier Types
- C++ Storage Classes
- C++ Operators
- C++ Loop Types
- C++ Decision Making
- C++ Functions
- C++ Numbers
- C++ Arrays
- C++ Strings
- C++ Pointers
- C++ References
- C++ Date & Time
- C++ Basic Input/Output
- C++ Data Structures
- C++ Object Oriented
- C++ Classes & Objects
- C++ Inheritance
- C++ Overloading
- C++ Polymorphism
- C++ Abstraction
- C++ Encapsulation
- C++ Interfaces
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
- Related Articles
- Longest Substring with At Most Two Distinct Characters in C++
- Longest Substring with At Least K Repeating Characters in C++
- Program to find length of longest substring which contains k distinct characters in Python
- Finding the longest Substring with At Least n Repeating Characters in JavaScript
- Find the longest substring with k unique characters in a given string in Python
- Longest string with two distinct characters in JavaScript
- Longest Substring Without Repeating Characters in Python
- Python – N sized substrings with K distinct characters
- C++ program to find string with palindrome substring whose length is at most k
- Program to find length of longest substring with character count of at least k in Python
- Finding longest substring between two same characters JavaScript
- Count number of substrings with exactly k distinct characters in C++
- Find the longest subsequence of an array having LCM at most K in Python
- Python program to find N-sized substrings with K distinct characters
- Longest Palindromic Substring

Advertisements