[LeetCode] Divide a String Into Groups of Size k

2138. Divide a String Into Groups of Size k

A string s can be partitioned into groups of size k using the following procedure:

  • The first group consists of the first k characters of the string, the second group consists of the next k characters of the string, and so on. Each element can be a part of exactly one group.
  • For the last group, if the string does not have k characters remaining, a character fill is used to complete the group.

Note that the partition is done so that after removing the fill character from the last group (if it exists) and concatenating all the groups in order, the resultant string should be s.

Given the string s, the size of each group k and the character fill, return a string array denoting the composition of every group s has been divided into, using the above procedure.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
class Solution {
public:
vector<string> divideString(string s, int k, char fill) {
string now = "";
vector<string> res;
for(auto& ch : s) {
now.push_back(ch);
if(now.size() == k) {
res.push_back(now);
now = "";
}
}
if(now != "") {
while(now.size() < k) now.push_back(fill);
res.push_back(now);
}
return res;
}
};
Author: Song Hayoung
Link: https://songhayoung.github.io/2025/06/23/PS/LeetCode/divide-a-string-into-groups-of-size-k/
Copyright Notice: All articles in this blog are licensed under CC BY-NC-SA 4.0 unless stating additionally.