【代码随想录字符串1】

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;
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值