题目描述
题目二:左旋转字符串
汇编语言中有一种移位指令叫做循环左移(ROL),现在有个简单的任务,就是用字符串模拟这个指令的运算结果。对于一个给定的字符序列S,请你把其循环左移K位后的序列输出。例如,字符序列S=”abcXYZdef”,要求输出循环左移3位后的结果,即“XYZdefabc”。是不是很简单?OK,搞定它!
[ 字符串的左旋转操作是把字符串前面的若干个字符转移到字符串的尾部,请定义一个函数实现字符串左旋转的功能。比如,输入字符串“abcdefg”和数字2,该函数将返回左旋转两位得到的结果“cdefgab” ]
实现
/**
* 把字符串分为两部分,0~n-1,n~len
* abcdefg,先翻转前面n位,ba cdefg
* 再翻转后面的, ba gfedc
* 全部翻转, cdefg ab
*/
public class C58_string_2_LeftRotateString {
public static String LeftRotateString(String str, int n) {
char[] chars = {};
if (str != null) {
chars = str.toCharArray();
int len = chars.length;
if (len > 0 && n > 0 && n < len) {
//翻转字符串前n个字符
reverse(chars, 0, n - 1);
//翻转字符串后面部分
reverse(chars, n, len - 1);
//翻转整个
reverse(chars, 0, len - 1);
}
}
return new String(chars);
}
// 翻转每个单词,同58-1
public static void reverse(char[] chars, int low, int high) {
while (low < high) {
// 前后对应位置对调
char temp = chars[low];
chars[low] = chars[high];
chars[high] = temp;
low++;
high--;
}
}
}
Test
public static void main(String[] args) {
String str = "abcdefg";
System.out.println(LeftRotateString(str, 2));
cdefgab
}