题解 | #单词替换#
单词替换
https://www.nowcoder.com/practice/5b58a04679d5419caf62c2b238e5c9c7
//巧用字符串查找函数str.find(要找的字符或字符串)
//字符串删除函数str.erase(删除位置,删除长度)
//字符串插入函数str.insert(插入位置,插入什么)
//我这个方法答案是对的,但如果我写成while(getline(cin,x))就说我运行超时了,不知道为什么
//您的程序未能在规定时间内运行结束,请检查是否循环有错或算法复杂度过大。
#include <iostream>
using namespace std;
int main() {
string x;
getline(cin,x);
x=' '+x+' ';//要在字符串前后加上空格,因为输入的测试数据中的a可能会在x中有多个重复的连续字符
string a,b;//原串里的a,用b替换
cin>>a>>b;
a=' '+a+' ';
b=' '+b+' ';
int lena=a.size();
int find=x.find(a);
while(find!=string::npos)
{
x.erase(find,lena).insert(find,b);
find=x.find(a);
}
int lenx=x.size();
x=x.substr(1,lenx);
cout<<x<<endl;
}