[LeetCode] Number of Divisible Substrings

2950. Number of Divisible Substrings

Each character of the English alphabet has been mapped to a digit as shown below.

img

A string is divisible if the sum of the mapped values of its characters is divisible by its length.

Given a string s, return the number of divisible substrings of s.

A substring is a contiguous non-empty sequence of characters within a string.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
class Solution {
public:
int countDivisibleSubstrings(string word) {
vector<int> cost{1,1,2,2,2,3,3,3,4,4,4,5,5,5,6,6,6,7,7,7,8,8,8,9,9,9};
int res = 0;
for(int i = 1; i <= 9; i++) {
unordered_map<int,int> freq{{0,1}};
int sum = 0;
for(auto& ch : word) {
int c = cost[ch-'a'];
sum += c - i;
res += freq[sum]++;
}
}
return res;
}
};
Author: Song Hayoung
Link: https://songhayoung.github.io/2024/01/13/PS/LeetCode/number-of-divisible-substrings/
Copyright Notice: All articles in this blog are licensed under CC BY-NC-SA 4.0 unless stating additionally.