Snowflake OA 面试真题解析:String Patterns(动态规划 / 计数)

18次阅读
没有评论

String Patterns

Given the length of a word wordLen and the maximum number of consecutive vowels it can contain maxVowels, determine how many unique words can be generated.

Words will consist of English alphabetic letters a through z only.

Vowels are {a, e, i, o, u}; consonants are the remaining 21 letters.

In the explanations, v and c represent vowels and consonants.

Return the number of possible words modulo 10^9 + 7.

Example

wordLen = 1
maxVowels = 1

There are 26 possibilities, one for each letter in the alphabet.

wordLen = 4
maxVowels = 1

Valid patterns include cccc, vccc, cvcc, ccvc, cccv, and vcvc.

Return the count modulo 10^9 + 7.

这题本质上是在统计长度为 wordLen 的字符串中,满足“连续元音不超过 maxVowels”的所有方案数。由于每个位置只有两类选择:5 个元音或 21 个辅音,所以可以把问题转化为按结尾连续元音个数进行状态转移的动态规划。常见做法是用 DFS + 记忆化或迭代 DP:状态通常表示当前已经构造到第几位、末尾连续元音有多少个;转移时如果放辅音,连续元音清零并乘 21,如果放元音,则连续元音加一并乘 5,但不能超过上限。答案需要对 10^9+7 取模,适合用 64 位中间变量避免溢出。

正文完
 0