元音辅音字符串计数

元音辅音字符串计数

 1process.stdin.resume();  2process.stdin.setEncoding('utf-8');  3let input = '';  4  5process.stdin.on('data', (data) => {  6 input += data;  7});  8  9process.stdin.on('end', () => { 10 let inputArray = input.split('\n'); 11 const word = inputArray[0]; 12 const k = parseInt(inputArray[1], 10); 13 14 function countValidSubstrings(word, k) { 15 const vowels = new Set(['a', 'e', 'i', 'o', 'u']); 16 let validSubstrings = 0; 17 18 // Iterate over all possible starting points of substrings 19 for (let start = 0; start < word.length; start++) { 20 let currentVowels = new Set(); 21 let consonantCount = 0; 22 23 // Iterate over all possible ending points of substrings starting at 'start' 24 for (let end = start; end < word.length; end++) { 25 const char = word[end]; 26 27 if (vowels.has(char)) { 28 currentVowels.add(char); 29 } else { 30 consonantCount++; 31 } 32 33 // Check if all vowels are present and the consonant count is exactly k 34 if (currentVowels.size === vowels.size && consonantCount === k) { 35 validSubstrings++; 36 } 37 38 // If we have more consonants than needed, no need to continue expanding the substring 39 if (consonantCount > k) { 40 break; 41 } 42 } 43 } 44 45 return validSubstrings; 46 } 47 48 const result = countValidSubstrings(word, k); 49 console.log(result); 50 process.exit(); 51});
process.stdin.resume(); process.stdin.setEncoding('utf-8'); let input = ''; process.stdin.on('data', (data) => { input += data; }); process.stdin.on('end', () => { let inputArray = input.split('\n'); const word = inputArray[0]; const k = parseInt(inputArray[1], 10); function countValidSubstrings(word, k) { const vowels = new Set(['a', 'e', 'i', 'o', 'u']); let validSubstrings = 0; // Iterate over all possible starting points of substrings for (let start = 0; start < word.length; start++) { let currentVowels = new Set(); let consonantCount = 0; // Iterate over all possible ending points of substrings starting at 'start' for (let end = start; end < word.length; end++) { const char = word[end]; if (vowels.has(char)) { currentVowels.add(char); } else { consonantCount++; } // Check if all vowels are present and the consonant count is exactly k if (currentVowels.size === vowels.size && consonantCount === k) { validSubstrings++; } // If we have more consonants than needed, no need to continue expanding the substring if (consonantCount > k) { break; } } } return validSubstrings; } const result = countValidSubstrings(word, k); console.log(result); process.exit(); });

Powered By 可尔物语

浙ICP备11005866号-12