Problem Statement
leetcode problem link
Brute Force [Accepted]
class Solution:
def divideString(self, s: str, k: int, fill: str) -> List[str]:
res = []
for i in range(0,len(s),k):
curr = s[i:i+k]
if len(curr) < k:
curr = ''.join(list(curr) + [fill] * (k - len(curr)))
res.append(curr[:])
return res
Editorial
Approach: Search for the starting index of each group
class Solution:
def divideString(self, s: str, k: int, fill: str) -> List[str]:
res = [] # grouped string
n = len(s)
curr = 0 # starting index of each group
# split string
while curr < n:
res.append(s[curr : curr + k])
curr += k
# try to fill in the last group
res[-1] += fill * (k - len(res[-1]))
return res
public class Solution {
public string[] DivideString(string s, int k, char fill) {
List<string> res = new List<string>(); // grouped string
int n = s.Length;
int curr = 0; // starting index of each group
// split string
while (curr < n) {
int end = Math.Min(curr + k, n);
res.Add(s.Substring(curr, end - curr));
curr += k;
}
// try to fill in the last group
string last = res[res.Count - 1];
if (last.Length < k) {
last += new string(fill, k - last.Length);
res[res.Count - 1] = last;
}
return res.ToArray();
}
}