[LeetCode] Count Beautiful Substrings I

2947. Count Beautiful Substrings I

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.

A 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.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
class Solution {
public:
int beautifulSubstrings(string s, int k) {
unordered_set<char> v{'a','e','o','i','u'};
int res = 0;
for(int i = 0; i < s.length(); i++) {
int vc = 0, cc = 0;
for(int j = i; j < s.length(); j++) {
if(v.count(s[j])) vc += 1;
else cc += 1;
if(vc == cc and vc * cc % k == 0) res += 1;
}
}
return res;
}
};
Author: Song Hayoung
Link: https://songhayoung.github.io/2023/11/26/PS/LeetCode/count-beautiful-substrings-i/
Copyright Notice: All articles in this blog are licensed under CC BY-NC-SA 4.0 unless stating additionally.