【陪伴式刷题】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)
相关推荐
CQU_JIAKE2 小时前
11.7[高体】
java·后端·spring
apcipot_rain3 小时前
C++转Java日记(04)
java·开发语言·c++
特立独行的猫A3 小时前
我给女儿写了个打字练习:一边敲键盘,一边把小学英语单词记牢
java·后端·python
憧憬成为java架构高手的小白5 小时前
LangGraph4j 实战(下)
java
天诰5 小时前
SA-K-11 检索会消失吗与四个未解问题
java·服务器·人工智能·python·机器学习·ai编程
这个昵称不容易9 小时前
SpringBoot「衣依」服装销售平台:144个Java文件180个接口,从挑衣服到收货评价整条链路都在
java·springboot·毕设
计算机毕设定制辅导-无忧学长9 小时前
《基于微信小程序的居家医疗陪护预约系统设计与实现》
java·spring boot·微信小程序·uniapp·居家医疗陪护预约系统
文丑颜不良啊10 小时前
LeetCode2221~2240题目解析
java·leetcode
秋饼10 小时前
Computer Use Agent Java 落地实战:感知-行动循环、执行器与安全围栏生产级实现
java·ai·技术分享·后端开发
Navigator_Z11 小时前
LeetCode //C - 1317. Convert Integer to the Sum of Two No-Zero Integers
c语言·算法·leetcode