您的位置:首页 > 其它

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 than
2k 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--;
}
}

}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: