剑指 Offer 58 - II. 左旋转字符串 - 力扣(LeetCode)
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) {
reverse(s.begin(), s.end());
//cout << s.size()-n << endl;
reverse(s.begin(), s.begin()+(s.size()-n));
reverse(s.begin()+(s.size()-n), s.end());
return s;
}
};
比较直接的:
class Solution {
public:
string reverseLeftWords(string s, int n) {
return s.substr(n) + s.substr(0, n);
}
};
其他的遍历,也可以,一次遍历就可以