Given a string
s
and an integer k
, return the length of the longest substring of s
such that the frequency of each character in this substring is greater than or equal to k
.Example 1:
Input: s = "aaabb", k = 3 Output: 3
Approach
Java
import java.util.HashMap;public class AtLeastKRepeatingCharacters {public static void main(String[] args) {String str = "aaabb";int k = 3;System.out.println(longestSubstring(str, k));}static int longestSubstring(String s, int k) {if (s.length() == 0 || k > s.length())return 0;int ans1 = 0;int j = 0;HashMap<Character, Integer> mp = new HashMap<Character, Integer>();for (int i = 0; i < s.length(); i++)mp.put(s.charAt(i), mp.getOrDefault(s.charAt(i), 0) + 1);while (j < s.length() && mp.get(s.charAt(j)) >= k)j++;if (j == s.length())return j;ans1 = longestSubstring(s.substring(0, j), k);while (j < s.length() && mp.get(s.charAt(j)) < k)j++;int ans2 = 0;if (j < s.length()) {ans2 = longestSubstring(s.substring(j), k);} elseans2 = 0;return Math.max(ans1, ans2);}}
C++
#include <bits/stdc++.h>using namespace std;int longestSubstring(string s, int k){if(s.size()==0||k>s.size())return 0;int ans1=0;int j=0;map<char,int> mp;for(int i=0;i<s.size();i++)mp[s[i]]++;while(j<s.size()&&mp[s[j]]>=k)j++;if(j==s.size())return j;ans1=longestSubstring(s.substr(0,j),k);while(j<s.size()&&mp[s[j]]<k)j++;int ans2=0;if(j<s.size()){ans2=longestSubstring(s.substr(j),k);}elseans2=0;return max(ans1,ans2);}int main(){string str="aaabb";int k=3;cout<<longestSubstring(str,k);return 0;}
No comments:
Post a Comment