leetcode -- 541. Reverse String II 【字符串反转 + 双指针 + 状态记录 + 数组与堆内存】
2017-07-21 11:22
633 查看
题目
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 than2k but greater than or equal to k characters, then reverse the first k characters and left the other as original.
Example:
Input: s = "abcdefg", k = 2 Output: "bacdfeg"
Restrictions:
The string consists of lower English letters only.
Length of the given string and k will in the range [1, 10000]
题意
给定一个字符串和整型k , 每隔 2k个字符,将 k个字符进行反转 ...(还有其他)分析及解答
字符串反转char 数组是存储在堆中的。
start,end 用来记录处理的状态。
public class Solution {
public String reverseStr(String s, int k) {
int start,end;
char[] sArray = s.toCharArray();
for(int i =0;i < sArray.length; i += 2*k){
start =i;
end = (start + k -1) < sArray.length -1 ? (start + k -1):(sArray.length -1);
reverseChar(sArray, start, end);
}
return String.valueOf(sArray);
}
public void reverseChar(char[] s,int start,int end){
while(start < end){
char tmp = s[start];
s[start] = s[end];
s[end] = tmp;
start++;
end--;
}
}
}
相关文章推荐
- leetcode 541. Reverse String II 反转字符串
- [LeetCode]541. Reverse String II(间隔反转字符串)
- leetcode -- 557. Reverse Words in a String III 【字符反转 + 字符数组 + 双指针 + 状态记录】
- LeetCode 541. Reverse String II (反转字符串 II)
- leetcode Reverse String II 反转字符串
- LeetCode 541. Reverse String II (字符串翻转)
- [leetcode, python] Reverse Words in a String 反转字符串
- [leetcode]541. Reverse String II
- [leetcode, python] Reverse Words in a String 反转字符串
- leetcode 541. Reverse String II(easy)
- 字符串反转--Leetcode Reverse String
- [leetcode, python] Reverse Words in a String 反转字符串
- [LeetCode] 344 Reverse String && 541 Reverse String II
- [leetcode, python] Reverse Words in a String 反转字符串
- 【LeetCode-面试算法经典-Java实现】【151-Reverse Words in a String(反转字符串中的单词)】
- 字符串反转 reverse-words-in-a-string @LeetCode
- [leetcode, python] Reverse Words in a String 反转字符串
- leetcode Reverse Words in a String III 反转字符串中的单词
- The Solution to Leetcode 541 Reverse String II
- leetcode解题之344. Reverse String & 345. Reverse Vowels of a String Java版(反转字符串)