Untitled
unknown
plain_text
a year ago
1.7 kB
5
Indexable
function countSubstringsWithKDistinctLetters(n, k, str) { let count = 0; let charCount = {}; let distinctCount = 0; // Initialize the first window for (let i = 0; i < k; i++) { if (!charCount[str[i]]) { charCount[str[i]] = 0; } charCount[str[i]]++; if (charCount[str[i]] === 1) { distinctCount++; } } if (distinctCount === k) { count++; } // Slide the window across the string for (let i = k; i < n; i++) { let startChar = str[i - k]; let endChar = str[i]; // Remove the start character of the previous window if (charCount[startChar] === 1) { distinctCount--; } charCount[startChar]--; // Add the end character of the current window if (!charCount[endChar]) { charCount[endChar] = 0; } charCount[endChar]++; if (charCount[endChar] === 1) { distinctCount++; } if (distinctCount === k) { count++; } } return count; } // Function to read input function main() { const readline = require('readline'); const rl = readline.createInterface({ input: process.stdin, output: process.stdout }); let input = []; rl.on('line', (line) => { input.push(line); }); rl.on('close', () => { let [n, k] = input[0].split(' ').map(Number); let str = input[1]; let result = countSubstringsWithKDistinctLetters(n, k, str); console.log(result); }); } // Call the main function to execute the program main();
Editor is loading...
Leave a Comment