(lintcode)第8题旋转字符串

要求:给定一个字符串和一个偏移量,根据偏移量旋转字符串(从左向右旋转)

样例

对于字符串 "abcdefg".
offset=0 => "abcdefg"
offset=1 => "gabcdef"
offset=2 => "fgabcde"
offset=3 => "efgabcd"

暂时只想到了暴力破解的方法(accept),感觉字符串要是特别长,移动起来还是耗费很长时间,以后再仔细考虑考虑。代码如下:

public class Solution {
    /**
     * @param str: an array of char
     * @param offset: an integer
     * @return: nothing
     */
    public void rotateString(char[] str, int offset) {
        // write your code here
        if(str.length==0)
            return;
        int realoffset=offset%str.length;
        char c;
        while(realoffset!=0){
            c=str[str.length-1];
            for(int i=str.length-1;i>0;i--)
            {
                str[i]=str[i-1];
            }
            str[0]=c;
            realoffset--;
        }
    }
}


你可能感兴趣的:(算法,lintcode)