首页 > 其他分享 >Count Beautiful Substrings II

Count Beautiful Substrings II

时间:2023-11-28 09:22:38浏览次数:33  
标签:Count Beautiful consonants right string vowels Substrings alpha beautiful

Count Beautiful Substrings II

You are given a string s and a positive integer k.

Let vowels and consonants be the number of vowels and consonants in a string.

A string is beautiful if:

  • vowels == consonants.
  • (vowels * consonants) % k == 0, in other terms the multiplication of vowels and consonants is divisible by k.

Return the number of non-empty beautiful substrings in the given string s.

substring is a contiguous sequence of characters in a string.

Vowel letters in English are 'a''e''i''o', and 'u'.

Consonant letters in English are every letter except vowels.

 

Example 1:

Input: s = "baeyh", k = 2
Output: 2
Explanation: There are 2 beautiful substrings in the given string.
- Substring "baeyh", vowels = 2 (["a",e"]), consonants = 2 (["y","h"]).
You can see that string "aeyh" is beautiful as vowels == consonants and vowels * consonants % k == 0.
- Substring "baeyh", vowels = 2 (["a",e"]), consonants = 2 (["b","y"]).
You can see that string "baey" is beautiful as vowels == consonants and vowels * consonants % k == 0.
It can be shown that there are only 2 beautiful substrings in the given string.

Example 2:

Input: s = "abba", k = 1
Output: 3
Explanation: There are 3 beautiful substrings in the given string.
- Substring "abba", vowels = 1 (["a"]), consonants = 1 (["b"]).
- Substring "abba", vowels = 1 (["a"]), consonants = 1 (["b"]).
- Substring "abba", vowels = 2 (["a","a"]), consonants = 2 (["b","b"]).
It can be shown that there are only 3 beautiful substrings in the given string.

Example 3:

Input: s = "bcdf", k = 1
Output: 0
Explanation: There are no beautiful substrings in the given string.

 

Constraints:

  • 1 <= s.length <= 5 * 104
  • 1 <= k <= 1000
  • s consists of only English lowercase letters.

 

解题思路

  这题难的地方是在数论的部分,把 $x^2 \equiv 0 \pmod{k}$,找到一个 $m$ 等价变成 $x \equiv 0 \pmod{m}$ 还是很难想到的。

  还是很容易知道是哈希表维护统计那一类题目。先将字符串构造出一个序列 $a$,如果 $\text{str}_i$ 是元音字母,则 $a_i = 1$,否则 $\text{str}_i$ 是辅音字母,则 $a_i = -1$。然后对序列 $a$ 求前缀和得到 $s$,当枚举到右端点 $r$,那么子数组的左端点 $l \in [0, r - 1]$ 就要满足 $s_r - s_l = 0$,即在左边找到满足 $s_l = s_r$ 的 $l$ 的数量。

  还要满足另外一个条件,$\left(\frac{r-l}{2}\right)^2 \equiv 0 \pmod{k}$,式子等价于 $\left(\frac{r-l}{2}\right)^2 = x \cdot k, \, x \in \mathbb{Z}$。继续推有

\begin{align*}
\left(\frac{r-l}{2}\right)^2 &= x \cdot k \\
(r-l)^2 &= 4 x \cdot k \\
(r - l)^2 &\equiv 0 \pmod{4k}
\end{align*}

  然后想到说能不能把左式的平方去掉,即找到一个 $m$,使得 $r - l \equiv 0 \pmod{m}$ 与上式的同余方程是等价的。对 $4k$ 进行质因数分解得到 $4k = p_1^{\alpha{1}} \cdot p_2^{\alpha{2}} \cdots p_n^{\alpha{n}}$,那么很明显对于每一项 $p_i^{\alpha{i}}$,$r-l$ 的质因数分解也必须含有 $p_i^{\beta{i}}$ 且 $2 \cdot \beta{i} \geq \alpha{i}$,即 $\beta{i} \geq \left\lceil \frac{\alpha{i}}{2} \right\rceil$。因此有 $m = p_1^{\left\lceil \frac{\alpha{1}}{2} \right\rceil} \cdot p_2^{\left\lceil \frac{\alpha{2}}{2} \right\rceil} \cdots p_n^{\left\lceil \frac{\alpha{n}}{2} \right\rceil}$,那么两个同余方程就可以等价了。

  因此把哈希表开成两维,当枚举完右端点 $r$,维护 $\text{mp}[s_r][r \bmod m] \gets \text{mp}[s_r][r \bmod m] + 1$ 即可。由于 $s_r$ 可能是负数所以需要加上一个偏移量 $n$。

  AC 代码如下,时间复杂度为 $O(\sqrt{k} + n)$:

class Solution {
public:
    long long beautifulSubstrings(string str, int k) {
        int n = str.size();
        vector<int> s(n + 1);
        set<char> st({'a', 'e', 'i', 'o', 'u'});
        for (int i = 1; i <= n; i++) {
            s[i] = s[i - 1];
            if (st.count(str[i - 1])) s[i]++;
            else s[i]--;
        }
        int m = 1;
        k <<= 2;
        for (int i = 2; i * i <= k; i++) {
            if (k % i == 0) {
                int s = 0;
                while (k % i == 0) {
                    s++;
                    k /= i;
                }
                s = s + 1 >> 1;
                while (s--) {
                    m *= i;
                }
            }
        }
        if (k > 1) m *= k;
        vector<vector<int>> mp(n * 2 + 1, vector<int>(m));
        long long ret = 0;
        for (int i = 1; i <= n; i++) {
            mp[s[i - 1] + n][(i - 1) % m]++;
            ret += mp[s[i] + n][i % m];
        }
        
        return ret;
    }
};

 

参考资料

  子数组统计的套路【力扣周赛 373】:https://www.bilibili.com/video/BV19N411j7Dj/

  赛事活动丨[第373 场周赛]式酱的解题报告:https://leetcode.cn/circle/discuss/k0kT9w/

标签:Count,Beautiful,consonants,right,string,vowels,Substrings,alpha,beautiful
From: https://www.cnblogs.com/onlyblues/p/17860810.html

相关文章

  • Atcoder-Countings4
    Atcoder-Countings4[ABC231G]BallsinBoxesProblem有\(n\)个盒子,初始时第\(i\)个盒子内有\(a_i\)个小球,进行\(k\)次操作后,每次操作等概率随机选择一个盒子放入一个小球,设\(k\)次操作后每个盒子的小球个数为\(b_i\),那么得分为\(\prod_{i=1}^nb_i\)。求出期望得分......
  • [ABC329C] Count xxx 题解
    插曲因为本人看错了题面,买看到一个子串只包含一种字母,所以切完D和E才回来发现很简单。问题翻译给你一个长度为\(N\)的字符串\(S\),由小写英文字母组成。求\(S\)的非空子串中有多少个是一个字符的重复。在这里,作为字符串的两个子串是相等的,即使它们是以不同的方式得到......
  • Python + BeautifulSoup 采集
    Python是一种非常流行的编程语言,也是开发网络爬虫和数据采集工具的首选语言。在Python中,有许多第三方库可以用于网络爬虫和数据采集,比如requests、beautifulsoup4、selenium等。下面是一个简单的例子,使用requests库采集一个网页:importrequests#发送GET请求response=......
  • ElasticSearch之cat count API
    读取当前存储的记录的数量。命令样例如下:curl-XGET"https://localhost:9200/_cat/count?v=true&pretty"--cacert$ES_HOME/config/certs/http_ca.crt-u"elastic:ohCxPH=QBE+s5=*lo7F9"执行结果输出如下:epochtimestampcount170074840914:06:490查看帮助,命......
  • MySQL中count()、sum()区别
    1、count0函数里面的参数是列名的的时候,会计算有值项的次数sum(函数里面的参数是列名的时候,会计算列名的值的和。2、两个函数在记录的列名的值为空或者是null时,都不会去统计即count(列名)和sum(列名)都不计入这条记录3、count()可以计算出行数,count(1)也可以计算出行数、1......
  • Netherlands: Soil Protection Act to keep tulips beautiful
      SoilpollutionmanagementintheNetherlands hasthreecharacteristics. Althoughthenaturalenvironment,populationanddevelopmentconditionsoftheNetherlandsareverydifferentfromthoseofChina,throughthedevelopmenttransformationandec......
  • Java的Integer.bitCount()源码分析
    本文部分参考:https://blog.csdn.net/weixin_42092787/article/details/106607426常规解法对于统计一个32位的二进制数值当中1的数量这个问题,常规解法如下:publicinthammingWeight(intn){intcount=0;for(inti=0;i<32;i++){n......
  • 09-基础SQL-DQL(数据查询语言)-聚合函数(count、max、min、avg、sum)
    DQL-介绍(常用)DQL英文全称是DataQueryLanguage(数据查询语言),数据查询语言用来查询数据库中表的记录查询关键字:SELECTDQL-语法......
  • T399753 counting problem(计数问题)题解
    LinkT399753countingproblem(计数问题)Question给出一个正整数\(n\),求\(AB+CD=n\)的方案数,\(A,B,C,D\)都是要求是正整数Solution考虑直接枚举\(ABCD\)显然是不切实际的那么就折半枚举设\(F_i\)表示两个数的乘积为\(i\)的方案数答案就是\(\sum\limits_{i=1......
  • mysql group by 执行原理及千万级别count 查询优化
    大家好,我是蓝胖子,前段时间mysql经常碰到慢查询报警,我们线上的慢sql阈值是1s,出现报警的表数据有7000多万,经常出现报警的是一个groupby的count查询,于是便开始着手优化这块,遂有此篇,记录下自己优化过程中的心得。优化慢sql前,肯定是要懂sql的查询逻辑,所以我先介绍下groupby语句......