【陪伴式刷题】Day 7|字符串|541.反转字符串 II(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 leave 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 <= 10^4
  • s consists of only lowercase English letters.
  • 1 <= k <= 10^4

英文版地址

leetcode.com/problems/re...

中文版描述

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

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

示例 1:

输入: s = "abcdefg", k = 2

输出: "bacdfeg"

示例 2:

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

输出: "bacd"

提示:

  • 1 <= s.length <= 10^4
  • s 仅由小写英文组成
  • 1 <= k <= 10^4

中文版地址

leetcode.cn/problems/re...

解题方法

俺这版

java 复制代码
class Solution {
    public String reverseStr(String s, int k) {
        char[] chars = s.toCharArray();
        for (int i = 0; i < chars.length; i += 2 * k) {
            reverse(chars, i, Math.min(chars.length, i + k)-1);
        }
        return new String(chars);

    }

    private void reverse(char[] chars, int fromIndex, int toIndex) {
        int right = toIndex;
        int left = fromIndex;
        while (left < right) {
            char temp = chars[left];
            chars[left] = chars[right];
            chars[right] = temp;
            left++;
            right--;
        }
    }
}

复杂度分析

  • 时间复杂度:O(n),其中 n 是字符串 s 的长度。
  • 空间复杂度:O(1),O(1)或 O(n),取决于使用的语言中字符串类型的性质。如果字符串是可修改的,那么我们可以直接在原字符串上修改,空间复杂度为 O(1),否则需要使用 O(n)的空间将字符串临时转换为可以修改的数据结构(例如数组),空间复杂度为 O(n)
相关推荐
xsyaaaan24 分钟前
leetcode-hot100-双指针:283移动零-11盛最多水的容器-15三数之和-42接雨水
算法·leetcode
HalvmånEver4 小时前
7.高并发内存池大页内存申请释放以及使用定长内存池脱离new
java·spring boot·spring
凤山老林4 小时前
SpringBoot 使用 H2 文本数据库构建轻量级应用
java·数据库·spring boot·后端
Tisfy5 小时前
LeetCode 1888.使二进制字符串字符交替的最少反转次数:前缀和O(1)
算法·leetcode·字符串·题解
赶路人儿5 小时前
UTC时间和时间戳介绍
java·开发语言
dreamread5 小时前
【SpringBoot整合系列】SpringBoot3.x整合Swagger
java·spring boot·后端
6+h5 小时前
【java】基本数据类型与包装类:拆箱装箱机制
java·开发语言·python
一直都在5725 小时前
Spring面经
java·后端·spring
xiaoye37085 小时前
如何在Spring中使用注解配置Bean的生命周期回调方法?
java·spring
闻哥5 小时前
深入Redis的RDB和AOF两种持久化方式以及AOF重写机制的分析
java·数据库·spring boot·redis·spring·缓存·面试