代码随想录算法【Day8】
Day8
344.反转字符串
class Solution { public: void reverseString(vector<char>& s) { int i = 0, j = s.size() - 1; char tmp; while(i < j){ //这里用swap(A, B)可以让代码更加简洁 tmp = s[i]; s[i] = s[j]; s[j] = tmp; i++; j--; } } };
541. 反转字符串II
class Solution { public: string reverseStr(string s, int k) { for(int i = 0; i < s.size(); i += (2 * k)){ if(i + k <= s.size()){ reverse(s.begin() + i, s.begin() + i + k); } else{ reverse(s.begin() + i, s.end()); } } return s; } };