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 / ksubstrings , 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.
We divide the string into equal parts, compute the sum of alphabet indices for each part, and map the sum modulo 26 back to a character. This is a direct simulation of the problem statement.
classSolution {
public: string hashString(string s, int k) {
int n = s.size();
string ans;
for (int i =0; i < n; i += k) {
int sum =0;
for (int j = i; j < i + k; ++j) sum += s[j] -'a';
ans += (char)('a'+ (sum %26));
}
return ans;
}
};
classSolution {
public String hashString(String s, int k) {
int n = s.length();
StringBuilder ans =new StringBuilder();
for (int i = 0; i < n; i += k) {
int sum = 0;
for (int j = i; j < i + k; ++j) sum += s.charAt(j) -'a';
ans.append((char)('a'+ (sum % 26)));
}
return ans.toString();
}
}
1
2
3
4
5
6
7
8
9
10
11
12
classSolution {
funhashString(s: String, k: Int): String {
val n = s.length
val ans = StringBuilder()
for (i in0 until n step k) {
var sum = 0for (j in i until i + k) sum += s[j] - 'a' ans.append(('a'.code + (sum % 26)).toChar())
}
return ans.toString()
}
}
1
2
3
4
5
6
7
8
classSolution:
defhashString(self, s: str, k: int) -> str:
n = len(s)
ans = []
for i in range(0, n, k):
total = sum(ord(c) - ord('a') for c in s[i:i+k])
ans.append(chr(ord('a') + (total %26)))
return''.join(ans)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
structSolution;
impl Solution {
pubfnhash_string(s: String, k: i32) -> String {
let n = s.len();
let s = s.as_bytes();
letmut ans = String::new();
let k = k asusize;
for i in (0..n).step_by(k) {
letmut sum =0;
for j in i..i+k {
sum += (s[j] -b'a') asi32;
}
ans.push((b'a'+ (sum %26) asu8) aschar);
}
ans
}
}