344.反转字符串
思路:虽然用reverse可以秒,但考察的是双指针。
题解:
class Solution {
public:
void reverseString(vector<char>& s) {
int left = 0;
int right = s.size() - 1;
while (left < right)
{
swap(s[left], s[right]);
++left;
--right;
}
}
};
541. 反转字符串 II
思路:上一题的进化版,完全套思路就行。
题解:
特别清晰的
class Solution {
public:
string reverseStr(string s, int k) {
int subnum = s.length() / k /2;
int restnum = s.length() % (k * 2);
for (int i = 0; i < subnum; ++i)
{
int left = i * k * 2;
int right = i * k * 2 + k - 1;
while (left < right)
{
swap(s[left], s[right]);
++left;
--right;
}
}
if (restnum < k)
{
int left = subnum * k * 2;
int right = s.length() - 1;
while (left < right)
{
swap(s[left], s[right]);
++left;
--right;
}
}
else
{
int left = subnum * k * 2;
int right = subnum * k * 2 + k - 1;
while (left < right)
{
swap(s[left], s[right]);
++left;
--right;
}
}
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);
continue;
}
reverse(s.begin()+i,s.begin()+s.size());
}
return s;
}
};
卡码网:54.替换数字
题目链接:替换数字
思路:求出替换后的长度,从右往左赋值,以免未遍历的字符被覆盖。
题解:
#include <iostream>
#include <string>
using namespace std;
int main(){
string s;
cin>>s;
int length = s.size();
int count = 0;
for (char ch : s)
{
if (ch >= '0' && ch <= '9')
++count;
}
int newlength = s.size() + 5 * count;
s.resize(newlength);
for (int i=0; i < length; ++i)
{
if (s[length - i - 1] <= '9' && s[length - i - 1] >= '0')
{
s[--newlength] = 'r';
s[--newlength] = 'e';
s[--newlength] = 'b';
s[--newlength] = 'm';
s[--newlength] = 'u';
s[--newlength] = 'n';
}
else
s[--newlength] = s[length - i - 1];
}
cout << s;
}