Leetcode 2949. Count Beautiful Substrings II

  • [Leetcode 2949. Count Beautiful Substrings II](#Leetcode 2949. Count Beautiful Substrings II)
    • [1. 解题思路](#1. 解题思路)
    • [2. 代码实现](#2. 代码实现)

1. 解题思路

这一题真的很丢脸,居然没有搞定,是看了大佬们的思路之后才想明白的,就感觉丢脸丢大了......

这道题讲道理挺简单的,而且相似类型的题目其实以前做过挺多的了,想不通但是为啥没有直接想到思路......

这道题的话如果没有平方整除 k k k的限制,只是要求元音和辅音字符相同的子串的数目,其实问题就非常简单,只要记录一下两者的差值,然后在相同项之间取开始和结束点即可,即 C n 2 C_n^2 Cn2种选择方法。

这里复杂也就是复杂在多了一个平方整除 k k k的限制要求,不过事实上这个也不麻烦的,我们在多一个字符串总长度的counter即可,要使得一个数的平方为 k k k的倍数,那么这个数一个是某一个数 p p p的倍数,且 p p p满足 p p p为最小的使得 p 2 ≡ 0 ( m o d k ) p^2 \equiv 0 (mod\ k) p2≡0(mod k)。

然后,我们重复上面的思路找一下每一种可能性的首尾节点的可能选取方式即可。

2. 代码实现

给出python代码实现如下:

python 复制代码
class Solution:
    def beautifulSubstrings(self, s: str, k: int) -> int:
        p = 1
        for i in range(1, k+1):
            if i * i % k == 0:
                p = i
                break

        cnt = defaultdict(int)
        cnt[(0, 0)] = 1
        delta, num = 0, 0
        for ch in s:
            if ch in "aeiou":
                delta += 1
                num += 1
            else:
                delta -= 1
            
            cnt[(delta, num % p)] += 1

        ans = 0
        for n in cnt.values():
            ans += n * (n-1) // 2
        return ans

提交代码评测得到:耗时196ms,占用内存20.7MB。

相关推荐
Espresso Macchiato15 小时前
Leetcode 3791. Number of Balanced Integers in a Range
leetcode hard·leetcode周赛482·leetcode 3791
Espresso Macchiato17 小时前
Leetcode 3782. Last Remaining Integer After Alternating Deletion Operations
迭代·leetcode hard·leetcode双周赛172·leetcode 3782
Espresso Macchiato21 小时前
Leetcode 3768. Minimum Inversion Count in Subarrays of Fixed Length
滑动窗口·leetcode hard·leetcode双周赛171·leetcode 3768
Espresso Macchiato1 天前
Leetcode 3785. Minimum Swaps to Avoid Forbidden Values
leetcode hard·leetcode周赛481·leetcode 3785
Espresso Macchiato1 天前
Leetcode 3786. Total Sum of Interaction Cost in Tree Groups
leetcode hard·leetcode 3786·leetcode周赛481
Espresso Macchiato1 个月前
Leetcode 3748. Count Stable Subarrays
算法·leetcode·职场和发展·leetcode hard·leetcode 3748·leetcode周赛476·区间求和
Espresso Macchiato2 个月前
Leetcode 3739. Count Subarrays With Majority Element II
leetcode hard·前序和数组·leetcode双周赛169·leetcode 3739
Espresso Macchiato2 个月前
Leetcode 3729. Count Distinct Subarrays Divisible by K in Sorted Array
leetcode·leetcode hard·容斥原理·leetcode 3729·leetcode周赛473·前序和数组
Espresso Macchiato2 个月前
Leetcode 3715. Sum of Perfect Square Ancestors
算法·leetcode·职场和发展·leetcode hard·树的遍历·leetcode 3715·leetcode周赛471
Espresso Macchiato3 个月前
Leetcode 3710. Maximum Partition Factor
leetcode·职场和发展·广度优先遍历·二分法·leetcode hard·leetcode 3710·leetcode双周赛167