erase 的时间复杂度是o(n)
void reverseString(vector<char>& s) {
//涉及到翻转,可以考虑双指针
for (int left = 0, right = s.size()-1; left < right; left++,right--) swap(s[left], s[right]);
}
string reverseStr(string s, int k) {
int n = s.size();
//注意:reverse的区间为左闭右开区间
for (int i = 0; i < n; i += 2*k){
if (i + k <= n){
reverse(s.begin()+i, s.begin()+i+k);
}else {
reverse(s.begin()+i, s.end());
}
}
return s;
}
替换数字(第八期模拟笔试)
#include <iostream>
using namespace std;
int main() {
string s;
while (cin >> s) {
int oldIndex = s.size()-1;
int count = 0;
for (int i=0; i <= oldIndex; 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';
s[newIndex--] = 'e';
s[newIndex--] = 'b';
s[newIndex--] = 'm';
s[newIndex--] = 'u';
s[newIndex--] = 'n';
}else{
s[newIndex--] = s[oldIndex];
}
oldIndex--;
}
cout << s << endl;
}
}
//难点:字符串去除多余的空格 可以使用快慢指针的方法, 空间复杂度o(1) 时间复杂度o(n)
//去除额外的0
void rmExtraSpace(string &s) {
int slow = 0;
int n = s.size();
for (int fast = 0; fast < n; fast++) {
if (s[fast] != ' '){
if (slow != 0) s[slow++] = ' '; //在不同单词之间添加空格
while(fast < n && s[fast] != ' '){
s[slow++] = s[fast++];
}
}
}
//重新规定s的长度
s.resize(slow);
}
//字符串翻转
void reverse(string &s, int left, int right) {
while (left < right) {
swap(s[left++], s[right--]);
}
}
string reverseWords(string s) {
//字符串去多余的空格
rmExtraSpace(s);
int n = s.size();
//先整体翻转,
reverse(s, 0, n-1);
//再对每一个单词进行翻转
int start = 0;
//注意,这里是 i <= n, 因为最后一个元素也要进行翻转
for (int i = 0; i <= n; i++) {
//遇到空格,则对上一个单词进行翻转
if (s[i] == ' '|| i == n){
reverse(s, start, i-1);
start = i+1;
}
}
return s;
}
右旋字符串(第八期模拟笔试)
#include <iostream>
#include <algorithm>
using namespace std;
//翻转字符串
void myReverse(string &s, int left, int right) {
while (left < right) {
swap(s[left++], s[right--]);
}
}
int main() {
int k; //右旋位数
string s;
cin >> k >> s;
int n = s.size();
myReverse(s, 0, n-1);
myReverse(s, 0, k-1);
myReverse(s, k, n-1);
// reverse(s.begin(), s.end());
// reverse(s.begin(), s.begin() + k);
// reverse(s.begin()+k, s.end());
cout << s << endl;
}