题解 | #单词替换#
单词替换
https://www.nowcoder.com/practice/5b58a04679d5419caf62c2b238e5c9c7
#include <iostream> using namespace std; #include<string> #include<vector> int main() { string a, b, c; getline(cin, a); cin >> b >> c; vector<int>q; vector<int>qq; qq.insert(qq.begin(), 0); for (int i = 0; i < a.size(); i++) { if (a[i] ==' ') qq.push_back(i + 1); } qq.push_back(a.size());//一开始漏掉了最后位置的判断 //在for循环中 一定要检查越界情况 比较常见 for (int i = 0; i < qq.size()-1; i++) { bool flag = true; for (int j = 0; j < b.size(); j++) { if ((qq[i + 1] - qq[i] - 1) != b.size()) flag = false;//导致这里的i+1越界 else { if (b[j] != a[qq[i] + j]) flag = false; } } if (flag == true) q.push_back(qq[i]); } for (int i = 0; i < q.size(); i++) { a.replace(q[i], b.size(), c); //每次替换操作后 原始字符串的位置就会发生变化 如果不改变位置就会报错 for (int j = i + 1; j < q.size(); j++) q[j] += c.size() - b.size(); } cout << a; }