substring:

Longest Substring With at Most Two Distinct Characters

Given a string s, find the length of the longest substring t that contains at most 2 distinct characters. Example 1 Input: "eceba" Output: 3 Explanation: t is "ece" which its length is 3. Example 2 Input: "ccaabbb" Output: 5 Explanation: t is "aabbb" which its length is 5. Solution class Solution { public int lengthOfLongestSubstringTwoDistinct(String s) { HashMap<Character, Integer> countMap = new HashMap<Character, Integer>(); int left = 0; int max = 0; for (int i = 0; i < s.

by lek tin in "algorithm" access_time 1-min read

Longest Substring With at Most K Distinct Characters

Given a string, find the length of the longest substring T that contains at most k distinct characters. Example 1 Input: s = "eceba", k = 2 Output: 3 Explanation: T is "ece" which its length is 3. Example 2 Input: s = "aa", k = 1 Output: 2 Explanation: T is "aa" which its length is 2. Solution class Solution { public int lengthOfLongestSubstringKDistinct(String s, int k) { Map<Character, Integer> countMap = new HashMap<>(); int left = 0; int max = 0; for(int i = 0; i < s.

by lek tin in "algorithm" access_time 2-min read

Count Number of Substrings With K Distinct Characters

Given a string, find the length of the longest substring T that contains at most k distinct characters. Example 1 Input: s = "eceba", k = 2 Output: 5 Explanation: "ec", "ce", "eb", "ba" and "ece" k distinct characters. Example 2 Input: s = "aa", k = 1 Output: 2 Explanation: "a" and "aa" have k distinct characters. import java.util.Arrays; public class CountKSubStr { // Function to count number of substrings // with exactly k unique characters int countkDist(String str, int k) { // Initialize result int res = 0; int n = str.

by lek tin in "algorithm" access_time 1-min read