题意:
输入一个字符串,在字符串中所有连续的数字子串左右各加一个*,输出处理后的字符串。
解法(while循环)
#include<bits/stdc++.h>
using namespace std;
int main(){
ios::sync_with_stdio(false);
string s;
while(cin>>s){
string ans;//答案字符串
int idx=0;//当前下标
while(idx<s.size()){
if(s[idx]>='0'&&s[idx]<='9'){
//如果是数字串
ans.push_back('*');
//在前面加一个*
while(idx<s.size()&&s[idx]>='0'&&s[idx]<='9'){
//扫描连续的数字串,作为一个整体
ans.push_back(s[idx]);
idx++;
}
ans.push_back('*');
//在后面加一个*
}else{
ans.push_back(s[idx]);//否则直接追加到答案字符串里
idx++;
}
}
cout<<ans<<endl;
}
return 0;
}
时间复杂度:
,其中
为字符串长度,显然,对于字符串每一位,我们只需要
的时间来处理,故时间复杂度为
空间复杂度:
,我们存储答案字符串需要
的空间,故空间复杂度为

京公网安备 11010502036488号