#include <iostream>
#include <string>
using namespace std;
class Solution
{
public:
string reverseStr(string s, int k)
{
if (s.size() <= k)
{
swapstring(s);
return s;
}
int pos = 0;
while (1)
{
string astring = s.substr(pos, k);
swapstring(astring);
s.replace(pos, k, astring);
pos += 2*k;
if (s.size()-pos <= k && s.size()-pos >0)
{
astring = s.substr(pos, k);
swapstring(astring);
s.replace(pos, k, astring);
return s;
}
if(pos>=s.size())
return s;
}
}
void swapstring(string &s)
{
int right = s.size() - 1;
int left = 0;
while (right - left > 0)
{
char temp = s[right];
s[right] = s[left];
s[left] = temp;
right--;
left++;
}
}
};
int main()
{
string s = "abcd";
Solution a;
string res = a.reverseStr(s, 2);
cout << res;
}
Leetcode541反转字符串Ⅱ(记录)C++
最新推荐文章于 2024-08-16 23:08:36 发布