题目链接:
力扣(LeetCode)官网 - 全球极客挚爱的技术成长平台
我的想法:
1,整体翻转,例如abcdefg -> gfedcba
2,单独翻转gfedc和ba -> cdefgab
我的代码:
class Solution {
public:
string reverseLeftWords(string s, int n) {
int end = s.size() - 1;
int index = end - n;
reverse(s, 0, end);
reverse(s, 0, index);
reverse(s, index+1, end);
return s;
}
void reverse(string &s, int start, int end)
{
while(start <= end)
{
swap(s[start++], s[end--]);
}
}
};
随想录代码:
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;
}
};