代码随想录算法训练营第七天
344.反转字符串
双指针交换。
class Solution {
public:
void reverseString(vector<char>& s) {
for(int i = 0, j = s.size() - 1; i < j; i++, j--) {
char temp = s[i];
s[i] = s[j];
s[j] = temp;
}
}
};
541. 反转字符串II
与上一题类似。
class Solution {
public:
void reverseAll(string& str, int begin, int end) {
for(int i = begin, j = end; i < j; i++, j--) {
swap(str[i], str[j]);
}
}
string reverseStr(string s, int k) {
for(int i = 0; i < s.size(); i += 2 * k) {
if(i + k > s.size() - 1) {
reverseAll(s, i, s.size() - 1);
}
else {
reverseAll(s, i, i + k - 1);
}
}
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 < s.size(); i++) {
if (s[i] >= '0' && s[i] <= '9') {
count++;
}
}
s.resize(s.size() + 5 * count);
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;
}
}