344反转字符串
void reverseString(vector<char>& s) {
char tmp;
int i = 0, j = s.size() - 1;
while (i<j)
{
tmp = s[i];
s[i] = s[j];
s[j] = tmp;
i++; j--;
}
}
swap库函数的实现:位运算法——按位异或
s[i] ^= s[j];
s[j] ^= s[i];
s[i] ^= s[j];
541反转字符串 II
string reverseStr(string s, int k) {
for (int i = 0; i < s.size(); i += (2 * k)) {
// 1. 每隔 2k 个字符的前 k 个字符进行反转
// 2. 剩余字符小于 2k 但大于或等于 k 个,则反转前 k 个字符
if (i + k <= s.size()) {
reverse(s.begin() + i, s.begin() + i + k);
}
else {
// 3. 剩余字符少于 k 个,则将剩余字符全部反转。
reverse(s.begin() + i, s.end());
}
}
return s;
}
卡码网54替换数字
对于线性数据结构,填充或者删除,后序处理会高效的多
#include<iostream>
#include <string>
using namespace std;
int main() {
string str;
cin >> str;
int cnt=0;
for (char a : str) {
if (a >= '0' && a <= '9')
cnt++;
}
int oldSize = str.size();
str.resize(oldSize + cnt * 5); //扩充字符串大小
int newSize = str.size();
for (int i = oldSize - 1, j = newSize - 1; i >= 0; i--, j--) {
if (str[i] < '0' || str[i]>'9') {
str[j] = str[i];
continue;
}
else
{
str[j] = 'r';
str[j-1] = 'e';
str[j-2] = 'b';
str[j-3] = 'm';
str[j-4] = 'u';
str[j-5] = 'n';
j -= 5;
}
}
cout << str;
}
151翻转字符串里的单词
难点:去除多余空格
string reverseWords(string s) {
int slow = 0, fast = 0;
while (s[fast] == ' ') //去除最前面空格
{
fast++;
}
for (; fast < s.size(); fast++) {
if (s[fast] != ' ')
s[slow++] = s[fast];
else { //去掉中间多余空格
if (s[fast] == s[fast - 1])
continue;
else
s[slow++] = ' ';
}
}
if (s[slow-1] == ' ') //去除最后多余空格
slow--;
s.resize(slow);
reverse(s.begin(), s.end());
int start = 0;
for (int i = 0; i <=s.size(); i++) {
if (i == s.size() || s[i] == ' ')
{
reverse(s.begin() + start, s.begin() + i); //左闭右开
start = i + 1;
}
}
return s;
}
卡码网55右旋转字符串
整体倒叙+子串倒叙
#include<iostream>
#include<algorithm>
using namespace std;
int main() {
int n;
string s;
cin >> n;
cin >> s;
reverse(s.begin(), s.end()); // 整体反转
reverse(s.begin(), s.begin() + n); // 先反转前一段,长度n
reverse(s.begin() + n, s.end()); // 再反转后一段
cout << s << endl;
}
标签:begin,slow,string,int,训练营,随想录,fast,算法,str
From: https://www.cnblogs.com/ddup-cpp/p/18105920