目录
344.反转字符串
class Solution {
public:
void reverseString(vector<char>& s) {
for (int i = 0, j = s.size() - 1; i < s.size()/2; i++, j--) {
swap(s[i],s[j]);
}
}
};
541. 反转字符串II
class Solution {
public:
string reverseStr(string s, int k) {
int loc = 0;
char tmpc;
//先把符合的前面几段都先反转了,剩下的就是另外两种情况了
while ((loc + 2 * k - 1) <= s.length() - 1) {
for (int i = loc, j = loc + k - 1; i < j; i++, j--) {
tmpc = s[i];
s[i] = s[j];
s[j] = tmpc;
}
loc = loc + 2 * k;
}
//另外两种情况,第一个是在 k 到 2k 直接
if (s.length() - loc >= k && s.length() - loc < 2 * k) {
for (int i = loc, j = loc + k-1; i < j; i++, j--) {
tmpc = s[i];
s[i] = s[j];
s[j] = tmpc;
}
}
else {
for (int i = loc, j = s.length() - 1; i < j; i++, j--) {
tmpc = s[i];
s[i] = s[j];
s[j] = tmpc;
}
}
return s;
}
};
54.替换数字
#include<iostream>
using namespace std;
int main() {
string s;
while (cin >> s) {
int count = 0; // 统计数字的个数
int sOldSize = s.size();
for (int i = 0; i < s.size(); i++) {
if (s[i] >= '0' && s[i] <= '9') {
count++;
}
}
// 扩充字符串s的大小,也就是每个空格替换成"number"之后的大小
s.resize(s.size() + count * 5);
int sNewSize = s.size();
// 从后先前将空格替换为"number"
for (int i = sNewSize - 1, j = sOldSize - 1; j < i; i--, j--) {
if (s[j] > '9' || s[j] < '0') {
s[i] = s[j];
} else {
s[i] = 'r';
s[i - 1] = 'e';
s[i - 2] = 'b';
s[i - 3] = 'm';
s[i - 4] = 'u';
s[i - 5] = 'n';
i -= 5;
}
}
cout << s << endl;
}
}
151.翻转字符串里的单词
class Solution {
public:
void reserve(string& s, int start, int end) {
for (int i = start, j = end; i < j; i++, j--) {
swap(s[i], s[j]);
}
}
void isEmpty(string& s) { //把最前面和后面的空格去掉
int slow = 0;
for (int i = 0; i < s.size(); i++) {
if (s[i] != ' ') {
if (slow != 0) {
s[slow++] = ' ';
}
while (i < s.size() && s[i] != ' ') {
s[slow++] = s[i++]; //把值赋给慢指针
}
}
}
s.resize(slow);
}
string reverseWords(string s) {
isEmpty(s);
reserve(s, 0, s.size() - 1); //把整个字符串反转了
int start = 0;
for (int i = 0; i <= s.size(); i++) {
if (i == s.size() || s[i] == ' ') {
reserve(s, start, i - 1);
start = i + 1; // i+1保证start是下一个元素的开头
}
}
return s;
}
};
55.右旋转字符串
#include<iostream>
#include<algorithm>
using namespace std;
int main() {
int n;
string s;
cin >> n;
cin >> s;
int len = s.size(); //获取长度
reverse(s.begin(), s.begin() + len - n); // 先反转前一段
reverse(s.begin() + len - n, s.end()); // 再反转后一段
reverse(s.begin(), s.end()); // 整体反转
cout << s << endl;
}