LeetCode 3271: Hash Divided String
Problem Description
Explanation:
To solve this problem, we need to divide the given string s
into substrings of length k
, calculate the hash value for each substring, find the corresponding character in the English alphabet based on the hash value, and append it to the result string.
- Iterate over each substring of length
k
in the input strings
. - Calculate the sum of hash values of characters in the substring.
- Find the hashed character by taking the sum modulo 26.
- Map the hashed character to the corresponding lowercase English alphabet character.
- Append the mapped character to the result string.
- Return the resulting string.
Time Complexity: O(n) where n is the length of the input string s
.
Space Complexity: O(n/k) where k is the length of each substring.
:
Solutions
class Solution {
public String hashDividedString(String s, int k) {
StringBuilder result = new StringBuilder();
for (int i = 0; i < s.length(); i += k) {
int sum = 0;
for (int j = 0; j < k; j++) {
int idx = i + j;
sum += s.charAt(idx) - 'a';
}
char hashedChar = (char) ((sum % 26) + 'a');
result.append(hashedChar);
}
return result.toString();
}
}
Loading editor...