carloscn / structstudy

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

leetcode541:反转字符串 II(reverse-string-ii) #115

Open carloscn opened 1 year ago

carloscn commented 1 year ago

问题描述

给定一个字符串 s 和一个整数 k,从字符串开头算起,每计数至 2k 个字符,就反转这 2k 字符中的前 k 个字符。

如果剩余字符少于 k 个,则将剩余字符全部反转。 如果剩余字符小于 2k 但大于或等于 k 个,则反转前 k 个字符,其余字符保持原样。  

示例 1:

输入:s = "abcdefg", k = 2 输出:"bacdfeg" 示例 2:

输入:s = "abcd", k = 2 输出:"bacd"  

提示:

1 <= s.length <= 104 s 仅由小写英文组成 1 <= k <= 104

来源:力扣(LeetCode) 链接:https://leetcode.cn/problems/reverse-string-ii

carloscn commented 1 year ago

问题分析

static int32_t reverse_string_ii(char *str, int32_t k)
{
    int32_t ret = 0;
    size_t str_len = 0;
    size_t delta = ((size_t)k) * 2;
    size_t i = 0, j = 0;
    char *dup_str = NULL;

    UTILS_CHECK_PTR(str);
    UTILS_CHECK_LEN(str_len = strlen(str));

    if (k <= 0) {
        ret = -1;
        LOG("input error!\n");
        goto finish;
    }
    dup_str = strdup(str);
    UTILS_CHECK_PTR(dup_str);

    while (i <= str_len) {
        i += delta;
        // if the left chars is less than k, all of the left chars shall be reversed.
        if (str_len - i < k) {
            ret = utils_str_reverse(dup_str + i);
        }
        // if the left chars is less than delta and more than or equal to k.
        else  {
            ret = utils_str_reserve_region(dup_str, i - delta, i - delta + 1);
        }
        UTILS_CHECK_RET(ret);
    }
    strcpy(str, dup_str);

finish:
    if (dup_str != NULL) {
        free(dup_str);
    }
    return ret;
}
carloscn commented 1 year ago

code:

https://github.com/carloscn/structstudy/blob/master/c_programming/str/35_reverse-string-ii_541.c https://github.com/carloscn/structstudy/blob/master/rust_programming/str/src/n35_reverse_tring_ii_541.rs