344.反转字符串
class Solution {
public:
void reverseString(vector<char>& s) {
int lens = s.size();
int right, left;
if (lens % 2 != 0)//奇数个
{
right = lens / 2 +1;
left = lens / 2 - 1;
}
else//偶数个
{
right = lens / 2;
left = lens / 2 - 1;
}
int i = 0, j = lens - 1;
while (i<=left&&j<=lens-1)
{
char temp = s[i];
s[i] = s[j];
s[j] = temp;
i++;
j--;
}
}
};
541.反转字符串||
class Solution {
public:
string reverseStr(string s, int k) {
int len = s.size();
for (int i =0; i < len; 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;
}
};
卡玛网54.替换数字
54. 替换数字(第八期模拟笔试) (kamacoder.com)### 额外的数组空间
#include<iostream>
#include<string>
using namespace std;
int main()
{
string result = "";
string s;
cin >> s;
for (int i = 0; i < s.length(); i++)
{
if (s[i] >= 'a' && s[i] <= 'z')
{
result += s[i];
}
else
{
result += "number";
}
}
cout << result;
}
双指针(不借用额外的数组空间)
#include<iostream>
#include<string>
using namespace std;
int main()
{
string s;
cin >> s;
int count = 0;
int OldIndex = s.size() - 1;
for (int i = 0; i < s.length(); i++)
{
if (s[i] >= '0' && s[i] <= '9')
{
count++;
}
}
s.resize(s.size() + count*5);
int NewIndex = s.size() - 1;//已扩容的下标
while (OldIndex >= 0)
{
if (s[OldIndex] >= '0' && s[OldIndex] <= '9')
{
s[NewIndex] = 'r';
NewIndex--;
s[NewIndex--] = 'e';
s[NewIndex--] = 'b';
s[NewIndex--] = 'm';
s[NewIndex--] = 'u';
s[NewIndex--] = 'n';
}
else
{
s[NewIndex] = s[OldIndex];
NewIndex--;
}
OldIndex--;
}
cout << s;
}
标签:344,string,int,反转,随想录,lens,字符串
From: https://www.cnblogs.com/FreeDrama/p/18397453