题目
字符串左移k位后的结果
解题
旋转三次
public class Solution {
public String LeftRotateString(String str,int n) {
if(str == null || str.length() <=1)
return str;
int len= str.length();
n = n%len;
char[] A = str.toCharArray();
reverse(A,0,len-1);
reverse(A,0,len-n-1);
reverse(A,len-n,len-1);
return String.valueOf(A);
}
// 旋转
public void reverse(char[] A,int left, int right){
int i = left;
int j = right;
while(i<j){
swap(A,i,j);
i++;
j--;
}
}
// 交换
public void swap(char[] A,int i,int j){
char ch = A[i];
A[i] = A[j];
A[j] = ch;
}
}
时间: 2024-10-21 11:45:13