1. 程式人生 > >[LintCode]8.旋轉字串

[LintCode]8.旋轉字串

給定一個字串和一個偏移量,根據偏移量旋轉字串(從左向右旋轉)

樣例

對於字串 "abcdefg".

offset=0 => "abcdefg"
offset=1 => "gabcdef"
offset=2 => "fgabcde"
offset=3 => "efgabcd"
思路:旋轉字串先呼叫翻轉字串函式,再分別旋轉三次可以達到效果
class Solution {
public:
    /**
     * @param str: a string
     * @param offset: an integer
     * @return: nothing
     */
    void rotateString(string &str,int offset){
        if(str.empty())
            return;
        int len = str.length();
        int off = offset % len;//求餘避免offset>len情況
        reverse(str, 0, len- off - 1);//翻轉字串前面n個字元
        reverse(str, len-off, len - 1);//翻轉字串的後面部分
        reverse(str, 0, len - 1);//翻轉整個字串 
    }
    void reverse(string &str,int start,int end) {  //翻轉字串
        for (int i = start,j = end; i < j; i++, j--) {
            char temp = str[i];
            str[i] = str[j];
            str[j] = temp;
        }
    }
};