当前位置:网站首页>力扣541-反转字符串2——双指针法
力扣541-反转字符串2——双指针法
2022-07-30 05:09:00 【张怼怼√】
题目描述
给定一个字符串 s 和一个整数 k,从字符串开头算起,每计数至 2k 个字符,就反转这 2k 字符中的前 k 个字符。
如果剩余字符少于 k 个,则将剩余字符全部反转。
如果剩余字符小于 2k 但大于或等于 k 个,则反转前 k 个字符,其余字符保持原样。
解题思路
这个题目和上一篇反转字符串是相同解法的
力扣344-反转字符串——双指针法力扣344-反转字符串——双指针法https://blog.csdn.net/weixin_44564247/article/details/126037243?csdn_share_tail=%7B%22type%22%3A%22blog%22%2C%22rType%22%3A%22article%22%2C%22rId%22%3A%22126037243%22%2C%22source%22%3A%22weixin_44564247%22%7D&ctrtid=dkBHs在本题中只是将字符串划分为2*k段,并对每段中的k段进行反转。
这里遍历字符串的时候,为了方便,可以将字符串转换为字符数组,遍历的时候 i 的取值每次不是i++,而且 i += 2*k ,然后在每个子区间内定义两个指针指向子区间的首尾,利用双指针法对其进行交换。
输入输出示例

代码
class Solution {
public String reverseStr(String s, int k) {
char[] charr = s.toCharArray();
int len = s.length();
char tem;
for(int i = 0; i < len; i +=2*k){
int start = i;
int stop = Math.min(start+k-1,len-1);
while(start <= stop){
tem = charr[start];
charr[start] = charr[stop];
charr[stop] = tem;
start++;
stop--;
}
}
return new String(charr);
}
}边栏推荐
猜你喜欢
![[3D Detection Series-PointRCNN] Reproduces the PointRCNN code, and realizes the visualization of PointRCNN3D target detection, including the download link of pre-training weights (starting from 0 and](/img/ca/17c047b8b1f030cc4ebb7e354070d9.png)
[3D Detection Series-PointRCNN] Reproduces the PointRCNN code, and realizes the visualization of PointRCNN3D target detection, including the download link of pre-training weights (starting from 0 and

Simulation problem (middle)

oracle触发器的自治事务

小程序npm包--API Promise化

RadonDB MySQL Kubernetes 2.2.0 发布!

mysql无法远程连接 Can‘t connect to MySQL server on ‘xxx.xxx.xxx.xxx‘ (10060 “Unknown error“)

pyinstaller打包程序所遇问题记录

Six, read application configuration + log configuration

Golang channel implementation principle

涂鸦Wi-Fi&BLE SoC开发幻彩灯带
随机推荐
webService interface
C语言中的基本库函数(qsort)
Dynamically bind href url
handler+message [message mechanism]
Some understanding of YOLOv7
[Verilog] HDLBits Problem Solution - Circuits/Combinational Logic
动态规划问题(完结篇)
Simulation problem (middle)
模拟问题(上)
Hexagon_V65_Programmers_Reference_Manual (11)
Learning of redis_Basic part
GO语言学习笔记一
(Hexagon_V65_Programmers_Reference_Manual(13)
(Hexagon_V65_Programmers_Reference_Manual(13)
全流程调度——Azkaban入门与进阶
双指针问题(下)
gnss rtcm rtklib Ntrip...
小程序使用npm包定制全局样式
ThinkPHP high imitation blue play cloud network disk system source code / docking easy payment system program
The Double Pointer Problem (Part 1)