对于一个字符串,和字符串中的某一位置,请设计一个算法,将包括i位置在内的左侧部分移动到右边,将右侧部分移动到左边。
给定字符串A和它的长度n以及特定位置p,请返回旋转后的结果。
测试样例:
"ABCDEFGH",8,4
返回:"FGHABCDE"
string rotateString(string A, int n, int p) {
// write code here
//剑指offer上的题目,两次翻转
//先进行局部翻转
int i = 0, j = p;
while(i < j)
swap(A[i++], A[j--]);
i = p + 1, j = n - 1;
while(i < j)
swap(A[i++], A[j--]);
//再整体翻转
i= 0, j = n - 1;
while(i < j)
swap(A[i++], A[j--]);
return A;
}
string rotateString(string A, int n, int p) {
// write code here
//剑指offer上的题目,两次翻转
//先进行局部翻转
reverse(A.begin(), A.begin()+p+1); //vector的迭代器支持 +
reverse(A.begin()+p+1, A.end());
//再整体翻转
reverse(A.begin(), A.end());
return A;
}
import java.util.*;
//两次分别翻转,再整体翻转。前面都说了很多了,就不赘述了,仅来签到而已
public class StringRotation {
public String rotateString(String str, int n, int p) {
String strA = str.substring(0,p+1);
String strB = str.substring(p+1,n);
StringBuilder sbA = new StringBuilder(strA);
StringBuilder sbB = new StringBuilder(strB);
strA = sbA.reverse().toString();
strB = sbB.reverse().toString();
StringBuilder sb = new StringBuilder(strA+strB);
String res = sb.reverse().toString();
return res;
}
}
classStringRotation {public:string rotateString(string A, intn, intp) {// write code herereturn(A+A).substr(p+1,n);}};
private void rotate(char[] str, int start, int end) {
if (str == null || start < 0 || end > str.length - 1)
return;
while (start < end) {
char temp = str[start];
str[start++] = str[end];
str[end--] = temp;
}
}
public String rotateString(String A, int n, int p) {
// write code here
char[] x = A.toCharArray();
rotate(x, 0, p);
rotate(x, p + 1, n - 1);
rotate(x, 0, n - 1);
return new String(x);
}
class StringRotation {
public:
string rotateString(string A, int n, int p) {
// write code here
reverse(A.begin(),A.begin()+p+1);
reverse(A.begin()+p+1,A.end());
reverse(A.begin(),A.end());
return A;
}
};