541. Reverse String II
来源:互联网 发布:华科软件学院 编辑:程序博客网 时间:2024/04/30 08:17
Given a string and an integer k, you need toreverse the first k characters for every 2k characters counting from the startof the string. If there are less than k characters left, reverse all of them.If there are less than 2k but greater than or equal to k characters, thenreverse the first k characters and left the other as original.
Input: s = "abcdefg", k = 2
Output: "bacdfeg"
翻译:给定一个字符串和一个整数k,你需要反转从字符串开始计数的每2k个字符的前k个字符。如果剩余少于k个字符,则将所有字符都反转。如果小于2k但大于或等于k个字符,则反转前k个字符,并将另一个作为原始字符。
直接按照上面的情况分类就好了,比较简单。自己定义一个从任意其实位置到结束位置的字符串反转的方法,然后分情况讨论,找好起始点就行了。代码如下:
public class Solution {
public static char[] reverse(char[] a,intstart,int end){
char temp;
int length=end-start;
//反转所有zifu
for(int i=0;i<length/2;i++){
temp=a[i+start];
a[i+start]=a[end-i-1];
a[end-i-1]=temp;
}
return a;
}
public String reverseStr(String s, int k) {
char []ch =s.toCharArray();
int length=ch.length;
int count=length;
int flag=0;
while(count>0){
if(count<k){
//反转所有zifu
ch=reverse(ch,flag,length);
break;
}
if(count>=k&&count<2*k){
ch=reverse(ch,flag,flag+k);
break;
}
if(count>=2*k){
ch=reverse(ch,flag,flag+k);
flag+=2*k;
count=length-flag;
}
}
return new String(ch);
}
}
- 541. Reverse String II
- 541. Reverse String II
- 541. Reverse String II
- 541. Reverse String II
- 541. Reverse String II
- 541. Reverse String II
- 541. Reverse String II
- 541. Reverse String II
- 541. Reverse String II
- 541. Reverse String II
- 541. Reverse String II
- 541. Reverse String II
- 541. Reverse String II
- 541. Reverse String II
- 541. Reverse String II
- String:541. Reverse String II
- leetcode 541. Reverse String II
- Leetcode-541. Reverse String II
- windows10中创建Direct3D11设备出现0x887a002d错误,提示应用程序请求的操作依赖于已缺失或不匹配的 SDK 组件
- iOS判断身份证号码是否正确
- word交叉引用格式改为上标
- pktgen使用总结
- Python TK 实现ping (二)
- 541. Reverse String II
- BZOJ1965: [Ahoi2005]SHUFFLE 洗牌
- Excel常用电子表格公式大全1-2
- 1121. Damn Single 解析
- [TCP/IP]常见的HTTP状态码
- JavaScript打印金字塔
- 不容易系列1
- 在 Fragment 中使用 React Native
- 6 guilty pleasures that are costing you