#反转字符串
class Solution { public: string reverseStr(string s, int k) { int i=0, left=0 ,right=0; while( right < s.size() ) { left = i+k; right = i +2*k; if( right < s.size() ) { reverse(s.begin()+i,s.begin()+left); i = right; }else if( left < s.size()) { reverse(s.begin()+i,s.begin()+left); }else { reverse(s.begin()+i,s.end()); } } return s; } };
二刷
class Solution { public: void rever(string &s ,int left ,int right) { while(left<right) { char tmp = s[right]; s[right] = s[left]; s[left] = tmp; left++; right--; } return; } string reverseStr(string s, int k) { int i=0; int flag=1;; for(i=0 ; i+k <s.size() ; i+=k) { if(flag==1) flag = 0; else if(flag == 0) { flag =1; continue; } int left = i; int right = left+k-1; rever(s,left,right); } if( flag==1 ) rever(s,i,s.size()-1); return s; } };