剑指offer 43:左旋转字符串

1 两倍串 截取

2 三次翻转

#include <iostream>
#include <string>



using namespace std;


class Solution
{
public:

    //两倍串截取
    string LeftRotationString(string str, int n) {
        if (str.length() == 0) {
            return " ";
        }
        n = n % str.length();
        int len = str.length();
        str = str + str;//两倍串
        return str.substr(n, len);//从下标为n截取长度为str.length()
    }

    // 三次翻转
    // abc defg
    // cba defg
    // cba gfed
    // defgabc
    string LeftRotationString2(string str, int n) {

        if (str.length() == 0) {
            return " ";
        }
        n = n % str.size();
        Reverse(str, 0, n - 1);

        Reverse(str, n, str.size() - 1);

        Reverse(str, 0, str.size() - 1);

        return str;
    }

    void Reverse(string &str, int left, int right) {
        while (left < right) {
            char temp = str[left];
            str[left] = str[right];
            str[right] = temp;
            //swap (str[left], str[right]);
            left++;
            right--;
        }
    }

    //牛客50%通过率


};

int main()
{
    string str = "heliopix";
    Solution s;

    cout << s.LeftRotationString2(str, 13) << endl;
    return 0;
}

猜你喜欢

转载自blog.csdn.net/liufanlibashanxi/article/details/85242597