1 class Solution { 2 public: 3 vector<long long> countKConstraintSubstrings(string s, int k, vector<vector<int>>& queries) { 4 int n = s.size(); 5 vector<int> count(2, 0); 6 vector<int> right(n, n); 7 vector<long long> prefix(n + 1, 0); 8 int i = 0; 9 for (int j = 0; j < n; ++j) { 10 count[s[j] - '0']++; 11 while (count[0] > k && count[1] > k) { 12 count[s[i] - '0']--; 13 right[i] = j; 14 i++; 15 } 16 prefix[j + 1] = prefix[j] + j - i + 1; 17 } 18 19 vector<long long> res; 20 for (auto& query : queries) { 21 int l = query[0], r = query[1]; 22 int i = min(right[l], r + 1); 23 long long part1 = 1LL * (i - l + 1) * (i - l) / 2; 24 long long part2 = prefix[r + 1] - prefix[i]; 25 res.push_back(part1 + part2); 26 } 27 return res; 28 } 29 };