leetcode_day8

本文最后更新于 2024年5月30日 下午

反转字符串II

按题意模拟即可,重写reverse方法,方便直接根据下标反转

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
string reverseStr(string s, int k) {
int begin = 0;
for(int i = 0;i < s.size();i += k) {
if(i % 2*k == 0) {
reverse(s, begin, i / 2);
begin = i;
}
}
return s;
}
void reverse(string &s, int begin, int end) {
if(begin >= end) return;
while(begin < end){
char c = s[begin];
s[begin] = s[end];
s[end] = c;
}
}

替换数字

预先扩充好空间,然后从后向前扫描

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
#include <iostream>
using namespace std;
int main() {
string s;
while (cin >> s) {
int sOldIndex = s.size() - 1;
int count = 0; // 统计数字的个数
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 sNewIndex = s.size() - 1;
// 从后往前将数字替换为"number"
while (sOldIndex >= 0) {
if (s[sOldIndex] >= '0' && s[sOldIndex] <= '9') {
s[sNewIndex--] = 'r';
s[sNewIndex--] = 'e';
s[sNewIndex--] = 'b';
s[sNewIndex--] = 'm';
s[sNewIndex--] = 'u';
s[sNewIndex--] = 'n';
} else {
s[sNewIndex--] = s[sOldIndex];
}
sOldIndex--;
}
cout << s << endl;
}
}
# 反转单词 思路比较巧,全部反转,然后再反转单词,这样就得到了词序反转,注意删除空格
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
class Solution {
public:
string reverseWords(string s) {
reverse(s.begin(), s.end());
auto it1 = s.begin();
auto it2 = s.begin();
while(it2 != s.end()) {
while(*it2 != ' ' && it2 != s.end()) it2++;
reverse(it1, it2);
while(*it2 == ' ' && it2 != s.end()) it2++;
it1 = it2;
}
it1=s.begin();
while(it1!=s.end()) {
if(it1==s.begin() && *it1 == ' ') s.erase(it1);
else if(*it1 == ' ' && *next(it1) == ' ') s.erase(it1);
else if(next(it1) == s.end() && *it1 == ' ') s.erase(it1);
else it1++;
}
return s;
}
};
# 右旋字符串 思路与反转单词差不多,整体局部反转活用就行
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
#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.end()); // 整体反转
reverse(s.begin(), s.begin() + n); // 先反转前一段,长度n
reverse(s.begin() + n, s.end()); // 再反转后一段

cout << s << endl;

}
字符串和数组很像,后面的kmp上难度,前面的比较简单,略过即可。


leetcode_day8
http://novelyear.github.io/2024/05/29/leetcode_day8/
作者
Leoo Yann
更新于
2024年5月30日
许可协议