Reverse String II
来源:互联网 发布:java创建线程runnable 编辑:程序博客网 时间:2024/06/10 00:34
1.题目
Given a string and an integer k, you need to reverse the first k characters for every 2k characters counting from the start of 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, then reverse the first k characters and left the other as original.
2.分析
看到这个题目,感觉有点绕- -,其实理解了题意,就不难了,就是按照给定的k,进行子串反转,不反转。。。。最后练成一个新串,返回。我的想法是,处理好边界,通过字符串长度与k,看看字符串长度包含几个k,计数反转,最后根据len/2再mod2结果是否为0,为0就进行反转。
3.实现
public class Solution {
public String reverseStr(String s, int k) {
StringBuffer result = new StringBuffer();
// 边界处理,输入为空
if(s==null){
return result.toString();
}
int len = s.length();
// 边界处理,字符串长度小于k
if(k>=len){
result.append(reverseString(s));
}else{
int count = len/k;
int num = len%k;
// int count = 0;
// 根据包含的k的个数遍历,进行反转
for(int i=0;i<count;i++){
if(i%2==0){
result.append(reverseString(s.substring(i*k, i*k+k)));
}else{
result.append(s.substring(i*k, i*k+k));
}
}
// 最后根据count的奇偶性
if(count%2==1){
result.append(s.substring(k*count,len));
}else{
result.append(reverseString(s.substring(k*count,len)));
}
}
return result.toString();
}
// 自定义字符串反转
public String reverseString(String str){
StringBuffer buffer = new StringBuffer();
if(str==null){
return buffer.toString();
}
int len = str.length();
for(int i=len-1;i>=0;i--){
buffer.append(str.charAt(i));
}
return buffer.toString();
}
}
4.总结
我的方法比较笨,用到的一些方法,时间效率比较低,但是也是一种解题思路,同时这种解题方法中,涉及很多工具类的使用。相比较而言,有一种解题思路我觉得还比较好:
public class Solution { public String reverseStr(String s, int k) { char[] arr = s.toCharArray(); int n = arr.length; int i = 0; while(i < n) { int j = Math.min(i + k - 1, n - 1); swap(arr, i, j); i += 2 * k; } return String.valueOf(arr); } private void swap(char[] arr, int l, int r) { while (l < r) { char temp = arr[l]; arr[l++] = arr[r]; arr[r--] = temp; } }}
这里面好像再字符处理前,使用Math.min(i+k-1,n-1)同时考虑了边界,又防止i越界,而swap采用字符交换来对子串进行反转,最后使用i += 2*k,使得所有不反转情况均包含在内。 - 541. Reverse String II
- 541. Reverse String II
- 541. Reverse String II
- Reverse String II
- 541. Reverse String II
- 541. Reverse String II
- Reverse String II
- Reverse String II
- Reverse String II
- oj541. Reverse String II
- 541. Reverse String II
- 541. Reverse String II
- 541. Reverse String II
- 541. Reverse String II
- 541. Reverse String II
- leetcode541. Reverse String II
- Reverse String II
- 541. Reverse String II
- Sublime Text 全程指引 by Lucida
- tensorflow Shapes and Shaping
- C# 装箱与拆箱
- Android Studio 使用技巧:修改默认build.gradle
- SPP(Spatial Pyramid Pooling in Deep Convolutional Networks for Visual Recognition)
- Reverse String II
- Scala => 用法总结
- Unity Shader入门精要笔记(十三):法线纹理
- 【转载】excel中自带的条件格式设置
- python3中无法导入cPickle
- iOS 音视频采集以及写入文件(swift)
- zcmu 1780——LoL?
- 算法<异或操作交换两个数的坑>
- c++:使用标准库的文本查询程序