一、问题描述
给定一个字符串,将字符串前面的若干个字符移到字符串的尾部。
如输入为“abcdef”输出为“defabc”
二、解题思路
解法一:蛮力移位
每一次将一个字符移到最后,执行n次
即第一次bcdefa,第二次cdefab
public static void shiftOne(char[] chars, int length) {
char t = chars[0];
for (int i = 0; i < length - 1; i++) {
chars[i] = chars[i + 1];
}
chars[length - 1] = t;
}
public static void rotate(char[] chars, int m) {
int n = chars.length;
while (m-- > 0) {// m代表循环的次数
shiftOne(chars, n--);// n代表要处理字符串的长度
}
}
时间复杂度O(mn),空间复杂度(1)
解法二:三步反转
- 将字符串分成2部分,X部分(abc)需要移动,Y部分(def)不需要移动
- 分别将X部分和Y部分反转得到(cba)(fed)
整体反转(defabc)
public static void ReverseString(char[] chars,int from,int to){ while(from<to){ char temp = chars[from]; chars[from++] = chars[to]; chars[to--] = temp; } } public static void LeftRotateString(char[] chars,int m,int n){ m%=n; ReverseString(chars,0,m-1); ReverseString(chars,m,n-1); ReverseString(chars,0,n-1); }
时间复杂度O(n),空间复杂度(1)
三、练习题
单词反转
输入“I am a student.” ,输出 “student. a am I”
解题思路
- 将整体反转(.tneduts a ma I)
- 再根据空格,将句子中的每个单词反转
假设输入为I am a student. 根据下面代码可以总结出循环语句
int pre = -1;
int next = -1;
pre = next;
next = 8;
ReverseString(chars, pre+1, next-1);
pre = next;
next = 10;
ReverseString(chars, pre+1, next-1);
pre = next;
next = 13;
ReverseString(chars, pre+1,next-1);
pre = next;
next = n+1;
ReverseString(chars, pre+1,next-1);
代码
public static void RatoteString(char[] chars,int n){
//整体反转
ReverseString(chars, 0, chars.length-1);
int pre = -1;
int next = -1;
//反转单词
for(int i = 0;i<=n;i++){
if(chars[i]==' '||i==n){
if(i==n){
i = n+1;
}
pre = next;
next = i;
ReverseString(chars, pre+1, next-1);
}
}
}
public static void ReverseString(char[] chars,int from,int to){
while(from<to){
char temp = chars[from];
chars[from++] = chars[to];
chars[to--] = temp;
}
}
测试
String str = "I am a very very good student.";
输出
student. good very very a am I