344.反转字符串
题目链接https://leetcode.cn/problems/reverse-string/
好像没啥说的,看看就行
class Solution {
public:
void reverseString(vector<char>& s) {
for(int i=0,j=s.size()-1;i<(s.size())/2;i++,j--){
char temp=s[i];
s[i]=s[j];
s[j]=temp;
}
}
};
541.反转字符串II
题目链接https://leetcode.cn/problems/reverse-string-ii/description/
动态数组里面用reverse 括号里面要用迭代器,不能像静态数组那种直接给下标
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.end());
}
return s;
}
};
54.替换数字https://programmercarl.com/kama54.%E6%9B%BF%E6%8D%A2%E6%95%B0%E5%AD%97.html
#include<iostream>
using namespace std;
int main() {
string s;
int count = 0;
while (cin >> s) {
int oldindex = s.size() - 1;
for (int i = 0; i < s.size(); i++) {
if (s[i] >= '0' && s[i] <= '9') {
count++;//计算有多少个数字
}
}
s.resize(s.size() + 5 * 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;
}
return 0;
}