剑指 Offer 58 - II 左旋转字符串

标签: 剑指 Offer 发布于:2022-02-27 20:22:14 编辑于:2022-02-27 20:27:01 浏览量:360

概述

https://leetcode-cn.com/problems/zuo-xuan-zhuan-zi-fu-chuan-lcof/

暴力遍历

注意对 k 取余。

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

原地 swap

class Solution {
public:
    string reverseLeftWords(string s, int n) {
        n %= s.size();
        reverse(s, 0, s.size() - 1);
        reverse(s, 0, s.size() - n - 1);
        reverse(s, s.size() - n, s.size() - 1);
        return s;
    }

    void reverse(string& s, int l, int r) {
        while (l < r) swap(s[l++], s[r--]);
    }
};

未经允许,禁止转载,本文源站链接:https://iamazing.cn/