题目描述:
给定一个字符串,要求将前n个字符移到字符串尾部。例如,将字符串“abcdef”的前3个字符‘a’,’b’,’c’移到字符串尾部,那么原字符串就变成”defabc”.
解法一:蛮力移位
public class RotateString {
//一个字符一个字符移动
public static void LeftShiftOne(char[] s){
char t = s[0]; //保存第一个字符
for(int i=1;i<s.length;i++){
s[i-1]=s[i];
}
s[s.length-1]=t;
}
//需要移动n个字符,调用n次LeftShiftOne函数
public static void LeftRotateString(char[] s, int n){
while(n!=0){
n--;
LeftShiftOne(s);
}
}
public static void main(String[] args) {
String str = "abcdef";
char[] s = str.toString().toCharArray();
LeftRotateString(s, 4);
System.out.println(String.valueOf(s));
}
}
efabcd
分析:对于长度为m的字符串,需要移动n个字符到尾部,那么总共需要m x n 次操作,同时需要设立一个变量保存第一个字符。
时间复杂度O(mn) , 空间复杂度 O(1).
解法二:三步反转
先把字符串分为两个部分,各自反转,最后整体反转。如给定字符串“abcdef”,若要将”abc”移动到”def”后面,分为3步:
- 将原字符串分为X和Y两部分,其中X是”abc”, Y是”def”.
- 将X和Y分别反转,X为”cba”,Y为”fed”.
- 将上述步骤得到的结构整体反转,即将”cbafed”反转,得到”defabc”.
public class RotateString {
public static void ReverseString(char[] s, int from, int to){
while(from < to){
char t = s[from];
s[from++] = s[to];
s[to--] = t;
}
}
public static void LeftRotateString(char[] s, int n){
n %= s.length;//若要左移动大于n位,那么与%n是等价的
ReverseString(s, 0, n-1);
ReverseString(s, n, s.length-1);
ReverseString(s, 0, s.length-1);
}
public static void main(String[] args) {
String str = "abcdef";
char[] s = str.toString().toCharArray();
LeftRotateString(s, 2);
System.out.println(String.valueOf(s));
}
}
cdefab
分析:时间复杂度为O(n),空间复杂度为O(1).