[LeetCode] Hash Divided String

3271. Hash Divided String

You are given a string s of length n and an integer k, where n is a multiple of k. Your task is to hash the string s into a new string called result, which has a length of n / k.

First, divide s into n / k substrings, each with a length of k. Then, initialize result as an empty string.

For each substring in order from the beginning:

  • The hash value of a character is the index of that character in the English alphabet (e.g., 'a' → 0, 'b' → 1, …, 'z' → 25).
  • Calculate the sum of all the hash values of the characters in the substring.
  • Find the remainder of this sum when divided by 26, which is called hashedChar.
  • Identify the character in the English lowercase alphabet that corresponds to hashedChar.
  • Append that character to the end of result.
1
2
3
4
5
6
7
8
9
10
11
12

class Solution {
public:
string stringHash(string s, int k) {
int n = s.length();
vector<char> sums(n/k);
for(int i = 0; i < n; i++) sums[i/k] = (sums[i/k] + s[i] - 'a') % 26;
string res = "";
for(int i = 0; i < n / k; i++) res.push_back(sums[i] % 26 + 'a');
return res;
}
};
Author: Song Hayoung
Link: https://songhayoung.github.io/2024/09/01/PS/LeetCode/hash-divided-string/
Copyright Notice: All articles in this blog are licensed under CC BY-NC-SA 4.0 unless stating additionally.