leetcode

Divide a String Into Groups of Size k - Link

Question Description

Given a string s, divide the string into groups of size k (except for the last group, which may be shorter). If the last group is shorter than k, fill it with the character fill.


Constraints


Approach


Dry Run

Example Input: s = “abcdef”, k = 3, fill = ‘x’

Step-by-step execution:

Another example: s = “abc”, k = 3, fill = ‘x’


Solution

class Solution {
    public String[] divideString(String s, int k, char fill) {
        int sLen = s.length();
        int aLen = sLen % k == 0 ? sLen / k : sLen / k + 1;
        String[] str = new String[aLen];

        int index = 0;
        for (int i = 0; i < sLen; i += k) {
            StringBuilder sb = new StringBuilder();
            for (int j = i; j < k + i; j++) {
                if (j < sLen) {
                    sb.append(s.charAt(j));
                } else {
                    sb.append(fill);
                }
            }
            str[index++] = sb.toString();
        }
        return str;
    }
}

Time and Space Complexity