II. Rotate the string to the left. The
question is simple but its own complexity is quite high.
Time complexity O(n) Space complexity O(n)
class Solution {
public:
string reverseLeftWords(string s, int n) {
int k=s.length();
string a;
for(int i=n;i<k;i++)
a+=s[i];
for(int i=0;i<n;i++)
a+=s[i];
return a;
}
};
Then come to a time complexity O(1) space complexity O(n)
class Solution {
public:
string reverseLeftWords(string s, int n) {
int k=s.length();
reverse(s.begin(),s.end());//先全部翻转变成gfedcba
reverse(s.begin(),s.begin()+k-n);//把前面部分翻转cdefgba
reverse(s.begin()+k-n,s.end());//再把后面翻转cdefgab
return s;
}
};