題目:給定字符串立帖,將字符串前幾位移動到字符串尾部州藕。
樣例:“abcdef” 吏奸,將前三位移動到字符串尾部没炒,則結(jié)果為“defabc”
解法1:蠻力移位
public class RevertString {
private static String shiftOne(String str) {
char[] chars = str.toCharArray();
char head = chars[0];
for (int i = 1; i < chars.length; i++) {
chars[i - 1] = chars[i];
}
chars[chars.length - 1] = head;
return String.valueOf(chars);
}
private static String revert(String str,int size) {
for (int i = 0; i < size; i++) {
str = shiftOne(str);
}
return str;
}
public static void main(String[] args) {
System.out.println(revert("abcdef",3));
}
}
該解法時間復(fù)雜度O(mn)
解法2:三步反轉(zhuǎn)法
private static String revertString(String str, int from, int to) {
char[] chars = str.toCharArray();
while (from < to) {
char head = chars[from];
chars[from++] = chars[to];
chars[to--] = head;
}
return String.valueOf(chars);
}
private static String revert(String str, int size) {
str = revertString(str, 0, size - 1);
str = revertString(str, size, str.length() - 1);
str = revertString(str, 0, str.length() - 1);
return str;
}
public static void main(String[] args) {
System.out.println(revert("abcdef", 3));
}
該解法時間復(fù)雜度O(n)
拓展:單詞反轉(zhuǎn),例如將"I work for money."反轉(zhuǎn)為"money. for work I"
private static String revert(String str, int from, int to) {
char[] chars = str.toCharArray();
while (from < to) {
char head = chars[from];
chars[from++] = chars[to];
chars[to--] = head;
}
return String.valueOf(chars);
}
public static void main(String[] args) {
String str = "I work for money.";
str = revert(str, 0, str.length() - 1);
String key = " ";
int start = 0;
int blankIndex = str.indexOf(key, start);
while (blankIndex != -1) {
str = revert(str, start, blankIndex - 1);
start = blankIndex + 1;
blankIndex = str.indexOf(key, start);
}
System.out.println(str);
}