剑指offer Leetcode 58 - II. 左旋转字符串

image-20201218190734326

解法一:遍历

思想:

​ 遍历存到res中

复杂度:

●时间:O(N)

●空间:O(N)

代码:

class Solution {
    
    
public:
    string reverseLeftWords(string s, int n) {
    
    
        string res = "";
        for(int i = n; i < s.size(); ++i)
            res += s[i];
        for(int i = 0; i < n; ++i)
            res += s[i];
        return res;
    }
};

解法二:substr

思想:

复杂度:

class Solution {
    
    
public:
    string reverseLeftWords(string s, int n) {
    
    
        string right = s.substr(0, n);
        string left = s.substr(n, s.size() - n);
        left += right;
        return left;
    }
};

解法三:三次反转

思想:

​ 操作是左闭右开的

​ begin()是开头元素,end()是末尾 + 1的元素

代码:

class Solution {
    
    
public:
    string reverseLeftWords(string s, int n) {
    
    
        reverse(s.begin(), s.begin() + n);
        reverse(s.begin() + n, s.end());
        reverse(s.begin(), s.end());
        return s;
    }
};

解法四:一行

class Solution {
    
    
public:
    string reverseLeftWords(string s, int n) {
    
    
        return (s + s).substr(n, s.size());
    }
};

猜你喜欢

转载自blog.csdn.net/qq_36459662/article/details/113955529
今日推荐