Skip to content

Navigation Menu

Sign in
Appearance settings

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Sign up
Appearance settings

Commit f7357b3

Browse files
#2138. Divide a String Into Groups of Size k
1 parent 3d03807 commit f7357b3

File tree

1 file changed

+55
-0
lines changed

1 file changed

+55
-0
lines changed

‎String/divide_string.py‎

Lines changed: 55 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,55 @@
1+
# A string s can be partitioned into groups of size k using the following procedure:
2+
3+
# The first group consists of the first k characters of the string, the second group
4+
# consists of the next k characters of the string, and so on. Each element can be
5+
# a part of exactly one group.
6+
# For the last group, if the string does not have k characters remaining, a character
7+
# fill is used to complete the group.
8+
# Note that the partition is done so that after removing the fill character from the
9+
# last group (if it exists) and concatenating all the groups in order, the resultant
10+
# string should be s.
11+
12+
# Given the string s, the size of each group k and the character fill, return a string
13+
# array denoting the composition of every group s has been divided into, using the above procedure.
14+
15+
16+
# Example 1:
17+
# Input: s = "abcdefghi", k = 3, fill = "x"
18+
# Output: ["abc","def","ghi"]
19+
# Explanation:
20+
# The first 3 characters "abc" form the first group.
21+
# The next 3 characters "def" form the second group.
22+
# The last 3 characters "ghi" form the third group.
23+
# Since all groups can be completely filled by characters from the string, we do not need to use fill.
24+
# Thus, the groups formed are "abc", "def", and "ghi".
25+
26+
# Example 2:
27+
# Input: s = "abcdefghij", k = 3, fill = "x"
28+
# Output: ["abc","def","ghi","jxx"]
29+
# Explanation:
30+
# Similar to the previous example, we are forming the first three groups "abc", "def", and "ghi".
31+
# For the last group, we can only use the character 'j' from the string. To complete this group, we add 'x' twice.
32+
# Thus, the 4 groups formed are "abc", "def", "ghi", and "jxx".
33+
34+
35+
# Constraints:
36+
37+
# 1 <= s.length <= 100
38+
# s consists of lowercase English letters only.
39+
# 1 <= k <= 100
40+
# fill is a lowercase English letter.
41+
42+
43+
from typing import List
44+
45+
class Solution:
46+
def divideString(self, s: str, k: int, fill: str) -> List[str]:
47+
length = len(s)//k
48+
rmdr = len(s)%k
49+
ans = []
50+
51+
for i in range(length):
52+
ans.append(s[i*k:k*(i+1)])
53+
if rmdr != 0:
54+
ans.append(s[-rmdr:].ljust(k, fill))
55+
return ans

0 commit comments

Comments
(0)

AltStyle によって変換されたページ (->オリジナル) /