LintCode 8. Roatate String

Description

Given a string(Given in the way of char array) and an offset, rotate the string by offset in place. (rotate from left to right)
offset >= 0
the length of str >= 0

給定一個字符串(以字符數組的形式給出)和一個偏移量,根據偏移量原地旋轉字符串(從左向右旋轉)

Example

Input: str=“abcdefg”, offset = 3
Output: str = “efgabcd”
Explanation: Note that it is rotated in place, that is, after str is rotated, it becomes “efgabcd”.

Input: str=“abcdefg”, offset = 0
Output: str = “abcdefg”
Explanation: Note that it is rotated in place, that is, after str is rotated, it becomes “abcdefg”.

Input: str=“abcdefg”, offset = 1
Output: str = “gabcdef”
Explanation: Note that it is rotated in place, that is, after str is rotated, it becomes “gabcdef”.

Input: str=“abcdefg”, offset =2
Output: str = “fgabcde”
Explanation: Note that it is rotated in place, that is, after str is rotated, it becomes “fgabcde”.

Input: str=“abcdefg”, offset = 10
Output: str = “efgabcd”
Explanation: Note that it is rotated in place, that is, after str is rotated, it becomes “efgabcd”.

Challenge

Rotate in-place with O(1) extra memory.

Submission

1. 使用substr函數

class Solution {
public:
    /**
     * @param str: An array of char
     * @param offset: An integer
     * @return: nothing
     */
    void rotateString(string &str, int offset) {
        // write your code here
        if (str.size() == 0){
            return;
        }
        offset = offset % str.size();
        str = str.substr(str.size() - offset, offset) 
            + str.substr(0, str.size() - offset);
    }
};

2. 兩兩交換的方式

2.1 窮舉法

class Solution {
public:
    /**
     * @param str: An array of char
     * @param offset: An integer
     * @return: nothing
     */
    void rotateString(string &str, int offset) {
        // write your code here
        int temple ;  //替換的值
        int cot = 0;     // 計數器
        int len = str.size();
        // 按順序依次進行交換,offset表示交換的輪數
        for(cot; cot < offset; cot++){
            temple = str[len - 1];
            for(int i = len - 1; i > 0; i--){
                str[i] = str[i - 1];  
            }
            str[0] = temple;
        }
    }
};

這種方式得到的結果的算法複雜度爲O(KN),若交換的次數過多(即K值大),計算量就超出限制的,這裏的結果是:Time Limit Exceeded

2.2 改進的窮舉法

交換的次數過大,可以考慮(K%N)的情況,交換N次不是等於不變嘛。Accepted

class Solution {
public:
    /**
     * @param str: An array of char
     * @param offset: An integer
     * @return: nothing
     */
    void rotateString(string &str, int offset) {
        // write your code here
        int temple ;  //替換的值
        int cot = 0;     // 計數器
        int len = str.size();
        
        if(len){
            offset = offset % len;
        }
        
        for(cot; cot < offset; cot++){
            temple = str[len - 1];
            for(int i = len - 1; i > 0; i--){
                str[i] = str[i - 1];
            }
            str[0] = temple;
        }
    }
};

2.3 直接交換法
待更新…

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章