方法1:三次翻转
public class Solution {
public String LeftRotateString(String str,int n) {
if(str.length()==0 || n>=str.length()){
return str;
}
char[] chars=str.toCharArray();
reverse(chars,0,n-1);
reverse(chars,n,chars.length-1);
reverse(chars,0,chars.length-1);
return new String(chars);
}
public void reverse(char[] chars,int i,int j){
while(i<j){
swap(chars,i++,j--);
}
}
public void swap(char[] chars,int i,int j){
char temp=chars[i];
chars[i]=chars[j];
chars[j]=temp;
}
}
方法2:substring()
public class Solution {
public String LeftRotateString(String str,int n){
if(str==null || n>str.length()){
return str;
}
return str.substring(n)+str.substring(0,n);
}
}
方法3:遍历
public class Solution {
public String LeftRotateString(String str,int n) {
if(str==null || n>str.length()){
return str;
}
char[] ch=str.toCharArray();
StringBuffer sb=new StringBuffer();
for(int i=n;i<str.length();i++){
sb.append(ch[i]);
}
for(int i=0;i<n;i++){
sb.append(ch[i]);
}
return sb.toString();
}
}