庞果网题目:http://hero.pongo.cn/Question/Details?ID=17&ExamID=17
题目详情
代码如下:
public class RightRotate {
private StringBuffer data = new StringBuffer();
private int length;
public RightRotate(String s){
this.data.append(s);
this.length = s.length();
}
/**循环右移,时间复杂度为O(n),空间复杂度为O(1)
* count记录已经改变的位数,temp1存储现在的字符,temp2存储下个字符,需要判断是否回到起点,如果回到起点就将起点加1
* @param offset,右移的位数
*/
public String rotate(int offset){
offset %= length;
if(offset == 0){
return data.toString();
}
int count = 1;
int start=0,pos = 0;
char temp1 = data.charAt(pos);
char temp2;
while(count <= length){
count++;
pos = (pos+offset)%length;
temp2 = data.charAt(pos);
data.setCharAt(pos, temp1);
if(pos == start){
start++;
pos++;
temp1 = data.charAt(pos);
continue;
}
temp1 = temp2;
}
return data.toString();
}
/**
* @param args
*/
public static void main(String[] args) {
RightRotate r = new RightRotate("abcdefgh");
String result = r.rotate(4);
System.out.println(result);
}
}
Output:
efghabcd