好二进制字符串的数量
Number of Good Binary Strings
题目详情
问题:好二进制字符串的数量
考察:数组、字符串
来源:Citadel
链接:https://www.jointaro.com/interviews/questions/number-of-good-binary-strings/
You are given a binary string s of length n and a positive integer k.
A substring of s is considered good if it contains at least k 1's.
Let nums[i] be the number of good substrings that start at index i. Return an integer array nums of length n such that nums[i] is the number of good substrings starting at index i.
A substring is a contiguous sequence of characters within a string.
Example 1:
Input: s = "1101101", k = 2 Output: [6,5,0,4,3,0,0] Explanation: Consider s = "1101101" and k = 2: - For i = 0: the good substrings starting at this index are "11", "110", "1101", "11011", "110110", "1101101", so nums[0] = 6. - For i = 1: the good substrings starting at this index are "10", "101", "1011", "10110", "101101", so nums[1] = 5. - For i = 2: there are no good substrings starting at this index, so nums[2] = 0. - For i = 3: the good substrings starting at this index are "11", "110", "1101", "11011", so nums[3] = 4. - For i = 4: the good substrings starting at this index are "11", "110", "1101", so nums[4] = 3. - For i = 5: there are no good substrings starting at this index, so nums[5] = 0. - For i = 6: there are no good substrings starting at this index, so nums[6] = 0.
Example 2:
Input: s = "10101", k = 3 Output: [0,0,0,0,0] Explanation: Consider s = "10101" and k = 3: - For i = 0: there are no good substrings starting at this index, so nums[0] = 0. - For i = 1: there are no good substrings starting at this index, so nums[1] = 0. - For i = 2: there are no good substrings starting at this index, so nums[2] = 0. - For i = 3: there are no good substrings starting at this index, so nums[3] = 0. - For i = 4: there are no good substrings starting at this index, so nums[4] = 0.
Constraints:
1 <= s.length <= 1051 <= k <= 105s[i]is either'0'or'1'.
解析
思路:令 dp[len] 表示构造长度 len 的方案数。可以从 len-zero 追加一段 0,或从 len-one 追加一段 1 转移,最后累加 low 到 high 的 dp。
复杂度:时间 O(high),空间 O(high)。