解题思路:
- 反转区间为前n的子串
- 反转区间为n到末尾的子串
- 反转整个字符串
方法一:
class Solution {
public:
void swapNum(string &s, int start, int end)
{
for(int i = start,j = end;i<j;i++,j--)
{
swap(s[i],s[j]);
}
}
string reverseLeftWords(string s, int n) {
swapNum(s,0,n-1);
swapNum(s,n,s.size()-1);
swapNum(s,0,s.size()-1);
return s;
}
};
方法二:
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;
}
};