541. Reverse String II

problem

solution

1
2
3
4
5
6
7
8
9
10
11
12
class Solution {
public:
void reverse(string& s, int l, int r ){
while(l<r) swap(s[l++], s[r--]);
}
string reverseStr(string s, int k) {
for(int i =0;i<s.size() ; i+=2*k){
reverse(s, i, min(i+k-1, int(s.size()-1)));
}
return s;
}
};

analysis

  • time complexity O(n)
  • space complexity O(1)