剑指 Offer 58 - II 左旋转字符串
概述
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--]);
}
};
Links: sword-offer-58-2