Skip to content

Commit 31aafd3

Browse files
authored
Update find-and-replace-in-string.cpp
1 parent 27920a9 commit 31aafd3

File tree

1 file changed

+12
-5
lines changed

1 file changed

+12
-5
lines changed

C++/find-and-replace-in-string.cpp

Lines changed: 12 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -1,18 +1,25 @@
1-
// Time: O(n * m), m is the number of targets
1+
// Time: O(n + m), m is the number of targets
22
// Space: O(n)
33

44
class Solution {
55
public:
66
string findReplaceString(string S, vector<int>& indexes, vector<string>& sources, vector<string>& targets) {
77
vector<pair<int, string>> bucket(S.size());
8-
for (auto i = 0; i < indexes.size(); ++i) {
8+
for (int i = 0; i < indexes.size(); ++i) {
99
if (S.find(sources[i], indexes[i]) == indexes[i]) {
1010
bucket[indexes[i]] = {sources[i].size(), targets[i]};
1111
}
1212
}
13-
for (int i = S.size() - 1; i >= 0; --i) {
14-
S.replace(i, bucket[i].first, bucket[i].second);
13+
string result;
14+
int i = 0, last = 0;
15+
for (i = 0; i < S.length(); ++i) {
16+
if (bucket[i].first) {
17+
result += S.substr(last, i - last);
18+
result += bucket[i].second;
19+
last = i + bucket[i].first;
20+
}
1521
}
16-
return S;
22+
result += S.substr(last, i - last);
23+
return result;
1724
}
1825
};

0 commit comments

Comments
 (0)