344. 反转字符串 - 力扣(LeetCode)
思路:双指针前后遍历,然后交换值
重点:原地修改,不能用额外字符串
class Solution {
public:
void reverseString(vector<char>& s) {
int n=s.size();
for(int i=0,j=n-1;i<j;i++,j--){
char t=s[i];
s[i]=s[j];
s[j]=t;
}
}
};
541. 反转字符串 II - 力扣(LeetCode)
思路:每2k个字符一个区间,所以每次向后移动2k个字符,然后反转前k个字符,最后的剩余不满足要求的全部反转
重点:reverse()库函数的使用,找对i每次位移的长度
class Solution {
public:
string reverseStr(string s, int k) {
int n=s.size();
for(int i=0;i<n;i+=2*k){
if(i+k<n){
reverse(s.begin()+i,s.begin()+i+k);//c++函数反转字符串
}else{
reverse(s.begin()+i,s.end());
}
}
return s;
}
};
54. 替换数字(第八期模拟笔试) (kamacoder.com)
思路:暴力解法遍历字符串找出数字,然后替换字符串。双指针法不需要额外字符,找出字符串中数字的长度,然后按照题目要求扩容字符
重点:双指针法需要把替换的字符串分解再依次添加到字符串
暴力解法:
#include<bits/stdc++.h>
using namespace std;
int main(){
ios::sync_with_stdio(0);
cin.tie(0);
cout.tie(0);
string s1,s2;
cin>>s1;
int n=s1.size();
for(int i=0;i<n;i++){
if(s1[i]>='0'&&s1[i]<='9'){
s2+="number";
continue;
}
s2+=s1[i];
}
cout<<s2;
return 0;
}
双指针解法:
#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;
}
}
总结
字符串问题多使用双指针法,找准遍历区间很重要