Given a string and an integer k, you need to reverse the first k characters for every 2k characters counting from the start of the string. If there are less than k characters left, reverse all of them. If there are less than 2k but greater than or equal to k characters, then reverse the first k characters and left the other as original.
Example:
Input: s = "abcdefg", k = 2 Output: "bacdfeg"
Restrictions:
- The string consists of lower English letters only.
- Length of the given string and k will in the range [1, 10000]
C++(19ms):
1 class Solution { 2 public: 3 string reverseStr(string s, int k) { 4 string res = "" ; 5 string t ; 6 int left = 0 ; 7 int m = 1 ; 8 while(left < s.size()){ 9 t = s.substr(left,k) ; 10 if(m%2){ 11 reverse(t.begin(),t.end()) ; 12 } 13 m++; 14 left+=k ; 15 res+=t ; 16 } 17 return res ; 18 } 19 };
C++(9ms):
1 class Solution { 2 public: 3 string reverseStr(string s, int k) { 4 for(int i = 0 ; i < s.size() ; i += 2*k){ 5 reverse(s.begin()+i, min(s.begin()+i+k , s.end())); 6 } 7 return s ; 8 } 9 };