LintCode-8.旋转字符串

旋转字符串

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

样例

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

挑战

在数组上原地旋转,使用O(1)的额外空间

标签

字符串处理

code

class Solution {
public:
    /**
     * @param str: a string
     * @param offset: an integer
     * @return: nothing
     */
    void rotateString(string &str,int offset){
        //wirte your code here
        if(str.empty())
            return;

        int off = offset % str.size();
        if(off != 0) {
            string suffix(off+1, '\0');
            int i, j, size=str.size();
            for(j=0,i=size-off; i<size; i++,j++) {
                suffix[j] = str[i];
            }
            for(i=size-off-1; i>=0; i--) {
                str[i+off] = str[i];
            }
            for(i=0; i<off; i++) {
                str[i] = suffix[i];
            }
        }
    }
};
posted @ 2017-05-04 17:11  LiBaoquan  阅读(981)  评论(0编辑  收藏  举报