#2138

Divide a String Into Groups of Size k

newbie · 205 · lc easy +16 · verified · 77.1% accepted · 796 likes · top 88%

Description

A string s can be split into groups of exactly k characters as follows:

- Consecutive chunks of k characters form each group from left to right.

- If the last group has fewer than k characters, pad it with the character fill until it reaches length k.

The split must satisfy: removing any padding from the last group and joining all groups recreates the original string s.

Given the string s, the group size k, and the fill character fill, return an array of strings representing each group.

Example 1:

Input: s = "abcdefghi", k = 3, fill = "x"
Output: ["abc","def","ghi"]
Explanation:
The first 3 characters "abc" form the first group.
The next 3 characters "def" form the second group.
The last 3 characters "ghi" form the third group.
Since all groups can be completely filled by characters from the string, we do not need to use fill.
Thus, the groups formed are "abc", "def", and "ghi".

Example 2:

Input: s = "abcdefghij", k = 3, fill = "x"
Output: ["abc","def","ghi","jxx"]
Explanation:
Similar to the previous example, we are forming the first three groups "abc", "def", and "ghi".
For the last group, we can only use the character 'j' from the string. To complete this group, we add 'x' twice.
Thus, the 4 groups formed are "abc", "def", "ghi", and "jxx".

Code

1
2
3