LeetCode 3271: Hash Divided String

StringSimulation

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.

  1. Iterate over each substring of length k in the input string s.
  2. Calculate the sum of hash values of characters in the substring.
  3. Find the hashed character by taking the sum modulo 26.
  4. Map the hashed character to the corresponding lowercase English alphabet character.
  5. Append the mapped character to the result string.
  6. 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...