LeetCode 2243: Calculate Digit Sum of a String
Problem Description
Explanation
- We will iterate over the string
s
in rounds until its length is less than or equal tok
. - In each round, we will divide
s
into groups of sizek
, calculate the digit sum of each group, and merge the results. - We repeat this process until the length of
s
is less than or equal tok
.
Time Complexity: O(n * m), where n is the length of the string s
and m is the number of rounds
Space Complexity: O(n), where n is the length of the string s
Solutions
class Solution {
public String calculateDigitSum(String s, int k) {
while (s.length() > k) {
StringBuilder sb = new StringBuilder();
for (int i = 0; i < s.length(); i += k) {
int sum = 0;
for (int j = i; j < Math.min(i + k, s.length()); j++) {
sum += s.charAt(j) - '0';
}
sb.append(sum);
}
s = sb.toString();
}
return s;
}
}
Loading editor...