题目链接:https://leetcode-cn.com/problems/reverse-string-ii/ 题目如下: 解一:
class Solution {
public:
string reverseStr(string s, int k) {
int size=s.size();
int flag=1,i;
char ch;
for(i=0;i<size;i+=k){
if(i+k<=size){
if(flag==1){
for(int j=0;j<k/2;j++){
ch=s[i+j];
s[i+j]=s[(i+k-1)-j];
s[(i+k-1)-j]=ch;
}
}
flag=-flag;
}
}
if(i>size&&flag==1){
int count=(size-1)-(i-k)+1;
for(int j=0;j<count/2;j++){
ch=s[(i-k)+j];
s[(i-k)+j]=s[(size-1)-j];
s[(size-1)-j]=ch;
}
}
return s;
}
};
解二:
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.begin()+s.size());
}
return s;
}
};
|