Given a string s
and an int k
, return an int representing the number of substrings (not unique) of s
with exactly k
distinct characters. If the given string doesn't have k
distinct characters, return 0.
https://leetcode.com/problems/subarrays-with-k-different-integers
Example 1:
Input: s = "pqpqs", k = 2
Output: 7
Explanation: ["pq", "pqp", "pqpq", "qp", "qpq", "pq", "qs"]
思路:这题思路很巧妙,我是看了上面那个 subarrays with k different integers 的花花视频才懂的。
直接求很难,但是我们可以转换成 f(k) - f(k-1) f(k)表示最多不大于k(at most k)的char的string的个数, at most k, 可以用sliding window的双指针来做,count 就是 j - i,表示以j - 1 为尾巴的subarray的个数;
public class numberOfUniqueChars {
public int getAtMostKCharacters(String s, int k) {
if(s == null || s.length() == 0) {
return 0;
}
int j = 0;
int[] counts = new int[256];
int c = 0;
int ans = 0;
for(int i = 0; i < s.length(); i++) {
// move j;
while(j < s.length() && c <= k) {
if(counts[s.charAt(j)] == 0 ) {
if(c == k) {
break;
}
c++;
}
counts[s.charAt(j)]++;
j++;
}
//update result;
ans += j - i;
// remove i;
counts[s.charAt(i)]--;
if(counts[s.charAt(i)] == 0) {
c--;
}
}
return ans;
}
public static void main(String[] args) {
/*
*
* Input: s = "pqpqs", k = 2
Output: 7
Explanation: ["pq", "pqp", "pqpq", "qp", "qpq", "pq", "qs"]
* */
numberOfUniqueChars numberOfUniqueChars = new numberOfUniqueChars();
String s = "pqpqs";
int ans1 = numberOfUniqueChars.getAtMostKCharacters(s, 2) - numberOfUniqueChars.getAtMostKCharacters(s, 1);
// ans = 7;
System.out.println("ans: " + ans1);
}
}