carloscn / structstudy

Leetcode daily trainning by using C/C++/RUST programming.
4 stars 1 forks source link

leetcode2138: Divide a String Into Groups of Size k #346

Open carloscn opened 1 year ago

carloscn commented 1 year ago

Description

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 character 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.

Example 1:

Input: s = "abcdefghi", k = 3, fill = "x" Output: ["abc","def","ghi"] Explanation: The first 3 characters "abc" form the first group. The next 3 characters "def" form the second group. The last 3 characters "ghi" form the third group. Since all groups can be completely filled by characters from the string, we do not need to use fill. Thus, the groups formed are "abc", "def", and "ghi".

Example 2:

Input: s = "abcdefghij", k = 3, fill = "x" Output: ["abc","def","ghi","jxx"] Explanation: Similar to the previous example, we are forming the first three groups "abc", "def", and "ghi". For the last group, we can only use the character 'j' from the string. To complete this group, we add 'x' twice. Thus, the 4 groups formed are "abc", "def", "ghi", and "jxx".

Constraints:

1 <= s.length <= 100 s consists of lowercase English letters only. 1 <= k <= 100 fill is a lowercase English letter.

carloscn commented 1 year ago

Analysis

int32_t divide_string(const char *s, int32_t k, char fill, char *o_list[], size_t *o_len)
{
    int32_t ret = 0;
    size_t in_len = 0;

    UTILS_CHECK_PTR(s);
    UTILS_CHECK_PTR(o_list);
    UTILS_CHECK_PTR(o_len);
    UTILS_CHECK_LEN(in_len = strlen(s));
    UTILS_CHECK_LEN(k);

    size_t j = 0;
    char *new_str = NULL;
    for (size_t i = 0; i < in_len; i ++) {
        if (i % k == 0) {
            UTILS_CHECK_PTR(new_str = (char *)calloc(k + 1, sizeof(char)));
            for (size_t m = 0; m < k; m ++) {
                new_str[m] =  (i + m < in_len) ? s[i + m] : fill;
            }
            o_list[j ++] = new_str;
        }
    }

    *o_len = j;

finish:
    return ret;
}
carloscn commented 1 year ago

Code

https://review.gerrithub.io/c/carloscn/structstudy/+/1168959 https://github.com/carloscn/structstudy/commit/6560de0f7f1cd5e1243c620ffd19c2701b42cad8