剑指offer(43)左旋转字符串
/*使用内置函数,用三个reverse(),先分别反转前k,再反转后面的,再整体翻转
public class Solution {
public String LeftRotateString(String str,int n) {
if(str == null || str.length() == 0 || n <= 0){
return str;
}
int length = str.length();
String strPart1 = str.substring(0, n);
String strPart2 = str.substring(n, length);
String reStrPart1 = new StringBuffer(strPart1).reverse().toString();
String reStrPart2 = new StringBuffer(strPart2).reverse().toString();
String temp = reStrPart1 + reStrPart2;
String res = new StringBuffer(temp).reverse().toString();
return res;
}
}
*/
public class Solution{//首尾互换,逐步往里
public String LeftRotateString(String str, int n){
if(str == null || str.length()== 0 || n <= 0 || n > str.length()){
return str;
}
char[] chs = str.toCharArray();
int length = chs.length;
reverse(chs, 0, n - 1);
reverse(chs, n, length - 1);
reverse(chs, 0, length - 1);
// return chs.toString();不可以,因为数组本身输出就不是一个一个的元素,而是地址表示
return new String(chs);
}
public void reverse(char[] chs, int start, int end){
char temp;
while(start < end){
temp = chs[end];
chs[end] = chs[start];
chs[start] = temp;
start++;
end--;
}
}
}