Leetcode 833. Find And Replace in String
You are given a string s and an array of indices. Each indices[i] indicates where a substring begins within s that you want to replace with another string. The list of source strings (sources[i]) and the list of target strings (targets[i]) are also provided.
To be more precise, if the substring in s starting at the index indices[i] and of length equal to len(sources[i]) matches sources[i], then you will replace that substring with targets[i]. If it doesn’t match, do nothing.
Return the modified string after all replacements have occurred.
indices be provided in any order, or will they always be sorted?s, indices, sources, or targets?Let’s assume the following example inputs for further clarity:
Input: s = "abcd", indices = [0, 2], sources = ["a", "cd"], targets = ["eee", "ffff"]
Output: "eeebffff"
#include <iostream>
#include <vector>
#include <string>
#include <algorithm>
std::string findReplaceString(std::string s, std::vector<int>& indices, std::vector<std::string>& sources, std::vector<std::string>& targets) {
// Create a list of tuples (index, source, target) and sort them by index
std::vector<std::tuple<int, std::string, std::string>> replacements;
for (int i = 0; i < indices.size(); ++i) {
replacements.emplace_back(indices[i], sources[i], targets[i]);
}
std::sort(replacements.begin(), replacements.end());
// Creat a result string builder
std::string result;
int lastIndex = 0;
for (const auto& [index, source, target] : replacements) {
// Append the non-modified parts to the result
result.append(s.substr(lastIndex, index - lastIndex));
// Check and replace the matching segment
if (s.substr(index, source.size()) == source) {
result.append(target);
lastIndex = index + source.size();
} else {
// If no match, just skip to the next index
lastIndex = index;
}
}
// Append the rest of the original string
result.append(s.substr(lastIndex));
return result;
}
int main() {
std::string s = "abcd";
std::vector<int> indices = {0, 2};
std::vector<std::string> sources = {"a", "cd"};
std::vector<std::string> targets = {"eee", "ffff"};
std::string updatedString = findReplaceString(s, indices, sources, targets);
std::cout << updatedString << std::endl; // Output: "eeebffff"
return 0;
}
O(n log n) where n is the number of replacements.s and replacements altogether take O(m + k) where m is the length of s and k is the total length of all sources and targets.Thus, the overall time complexity is dominated by the sorting step, resulting in:
O(n log n + m + k)
Got blindsided by a question you didn’t expect?
Spend too much time studying?
Or simply don’t have the time to go over all 3000 questions?