Skip to content

Commit aabc110

Browse files
authored
Create 2138-divide-a-string-into-groups-of-size-k.java
1 parent 8c4ebec commit aabc110

File tree

1 file changed

+39
-0
lines changed

1 file changed

+39
-0
lines changed
Lines changed: 39 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,39 @@
1+
/*
2+
Problem: Divide a String Into Groups of Size k
3+
LeetCode: https://leetcode.com/problems/divide-a-string-into-groups-of-size-k/
4+
5+
Given a string s, divide the string into groups of size k (except for the last group, which may be shorter).
6+
If the last group is shorter than k, fill it with the character fill.
7+
8+
Approach:
9+
- Calculate the number of resulting groups based on the string length and k.
10+
- Iterate over the string in steps of k.
11+
- For each group, build a substring of length k.
12+
- If characters run out, append the fill character.
13+
- Store each group in the result array and return it.
14+
15+
Time Complexity: O(n) where n is the length of string s.
16+
Space Complexity: O(n) for storing the resulting array of strings.
17+
*/
18+
19+
class Solution {
20+
public String[] divideString(String s, int k, char fill) {
21+
int sLen = s.length();
22+
int aLen = sLen % k == 0 ? sLen / k : sLen / k + 1;
23+
String[] str = new String[aLen];
24+
25+
int index = 0;
26+
for (int i = 0; i < sLen; i += k) {
27+
StringBuilder sb = new StringBuilder();
28+
for (int j = i; j < k + i; j++) {
29+
if (j < sLen) {
30+
sb.append(s.charAt(j));
31+
} else {
32+
sb.append(fill);
33+
}
34+
}
35+
str[index++] = sb.toString();
36+
}
37+
return str;
38+
}
39+
}

0 commit comments

Comments
 (0)