Leetcode 2138. Divide a String Into Groups of Size k
You are given a string s
of length n
and an integer k
. You need to divide the string into groups of size k
. Each group should be a substring
of s. You should also ensure that the last group is the same size as all the other groups or longer. If the last group of the string is shorter than k
` characters, pad additional characters to ensure all groups are of the same length.
For instance, if the last group is shorter than k
characters, fill the remaining positions with the character '*'
.
s
be empty?k
be larger than the length of the string s
?Assuming that k
will always be a positive integer and the padding character is '*'
.
k
.k
from the current starting index and add it to the list.k
. If so, pad it with ' * '
to make its length equal to k
.import java.util.ArrayList;
import java.util.List;
public class Solution {
public List<String> divideString(String s, int k, char fill) {
List<String> result = new ArrayList<>();
int n = s.length();
for (int i = 0; i < n; i += k) {
StringBuilder group = new StringBuilder();
int remainingLength = (i + k <= n) ? k : n - i;
group.append(s, i, i + remainingLength);
while (group.length() < k) {
group.append(fill);
}
result.add(group.toString());
}
return result;
}
public static void main(String[] args) {
Solution sol = new Solution();
System.out.println(sol.divideString("abcdefghi", 3, '*')); // Output: [abc, def, ghi]
System.out.println(sol.divideString("abcdefghij", 3, '*')); // Output: [abc, def, ghi, j**]
}
}
s
. We iterate through each character of the string exactly once to construct the substrings.This approach ensures that each group is correctly padded and all groups are of size k
or extended to size k
if the last group is shorter than k
characters.
Got blindsided by a question you didn’t expect?
Spend too much time studying?
Or simply don’t have the time to go over all 3000 questions?