每日题解——2021-8-20

156 阅读1分钟

这是我参与8月更文挑战的第20天,活动详情查看:8月更文挑战

541. 反转字符串 II

给定一个字符串 s 和一个整数 k,从字符串开头算起,每 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

541. Reverse String II

Given a string s and an integer k, reverse the first k characters for every 2k characters counting from the start of the string.

If there are fewer than k characters left, reverse all of them. If there are less than 2k but greater than or equal to k characters, then reverse the first k characters and left the other as original.

 

Example 1:

Input: s = "abcdefg", k = 2
Output: "bacdfeg"

Example 2:

Input: s = "abcd", k = 2
Output: "bacd"

  Constraints:

1 <= s.length <= 104
s consists of only lowercase English letters.
1 <= k <= 104

解题思路

我们直接按题意进行模拟:反转每个下标从 2k2k 的倍数开始的,长度为 kk 的子串。若该子串长度不足 kk,则反转整个子串。 复杂度分析

时间复杂度:O(n)O(n),其中 nn 是字符串 ss 的长度。

空间复杂度:O(1)O(1) 或 O(n)O(n),取决于使用的语言中字符串类型的性质。如果字符串是可修改的,那么我们可以直接在原字符串上修改,空间复杂度为 O(1)O(1),否则需要使用 O(n)O(n) 的空间将字符串临时转换为可以修改的数据结构(例如数组),空间复杂度为 O(n)O(n)。

代码

var reverseStr = function(s, k) {
    const n = s.length;
    const arr = Array.from(s);
    for (let i = 0; i < n; i += 2 * k) {
        reverse(arr, i, Math.min(i + k, n) - 1);
    }
    return arr.join('');
};

const reverse = (arr, left, right) => {
    while (left < right) {
        const temp = arr[left];
        arr[left] = arr[right];
        arr[right] = temp;
        left++;
        right--;
    }
}