对于一个给定的字符序列S,请把其循环左移 K 位后的序列输出。例如,字符序列 S= "abcXYZdef",要求输出循环左移 3 位后的结果,即 "XYZdefabc"
解题思路
最简单的做法,拼接字符串
public class Solution {
public String LeftRotateString(String str,int n) {
if(str == null || str.length() == 0) {
return "";
}
StringBuilder strb = new StringBuilder(str);
String leftStr = strb.substring(0, n % str.length());
strb.delete(0, n % str.length());
strb.append(leftStr);
return strb.toString();
}
}
另一种思路就是利用字符串翻转,假设字符串 abcdef,n = 3,设 X = abc,Y = def,所以字符串可以表示成 XY,如题干,问如何求得 YX。假设 X 的翻转为 XT,XT = cba,同理 YT = fed,那么 YX = (XTYT)T,三次翻转后可得结果
public class Solution {
public String LeftRotateString(String str,int n) {
if(str == null || str.length() == 0) {
return "";
}
if(n > str.length()) {
n %= str.length();
}
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 start, int end) {
while(start < end) {
char temp = chars[start];
chars[start] = chars[end];
chars[end] = temp;
start++;
end--;
}
}
}
|