1.反转字符串
题目链接/文章讲解/视频讲解:代码随想录
代码:
class Solution {
public:
void reverseString(vector<char>& s) {
int left = 0;
int right = s.size() - 1;
while(left < right){
char temp = s[left];
s[left] = s[right];
s[right] = temp;
left++;
right--;
}
}
};
note:没什么好说的
2.反转字符串2
题目链接/文章讲解/视频讲解:代码随想录
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);
}else{
reverse(s.begin() + i,s.end());
}
}
return s;
}
};
note:要注意题目上的要求,如果剩下的够k个就翻转前k个;如果没够,就全部翻转
3.替换数字
题目链接/文章讲解:代码随想录
#include <iostream>
#include <string>
using namespace std;
int main(){
string s;
while (cin >> s) {
int numCount = 0; // 统计数字的个数
for (int i = 0; i < s.size(); i++) {
if (s[i] >= '0' && s[i] <= '9') {
numCount++;
}
}
int sOld = s.size() - 1;
s.resize(s.size() + numCount * 5);
int sNew = s.size() - 1;
int right = sNew;
for(int left = sOld; left >= 0; left--){
if(s[left] >= '0'&& s[left] <= '9'){
s[right--] = 'r';
s[right--] = 'e';
s[right--] = 'b';
s[right--] = 'm';
s[right--] = 'u';
s[right--] = 'n';
}else{
s[right--] = s[left];
}
}
cout << s << endl;
}
}
note:边界条件写错了left应该是>=0,我写成了大于0.