从给定的索引开始替换给定的字符串
给定一个字符串S ,你需要对其进行Q替换操作。
每个替换操作都有3个参数:一个起始索引i,一个源词x和一个目标词y。规则是:如果x在原始 字符串S中的位置i开始,那么用y替换x的那个位置。
注意: 所有这些操作都是同时发生的。保证不会有任何重叠的替换:例如,S = "abc", indexes = [0, 1], sources = ["ab", "bc"] 不是一个有效的测试案例。
例子。
输入。 S = "gforks", Q = 2, index[] = {0, 4}, sources[] = {"g", "ks"}, targets[] = {"geeks", "geeks"}
输出:geeksforgeeks
解释。 "g "从索引0开始,所以,它被 "geeks "重新置换。
同样地,"ks "从索引4开始,被 "geeks "取代。输入。 S = "gforks", Q = 2, index[] = {0, 3}, sources[] = {"g", "ss"}, targets[] = {"geeks", "geeks"}
输出: geeksforks
解释。 "g "从索引0开始,所以,它被 "geeks "取代。
"ss "在原始S中不是从索引3开始的,所以它没有被替换。
办法这个问题可以根据以下思路来解决。
创建一个额外的字符串,对每一个操作检查是否可以替换。如果可能,就进行修改。
按照下面提到的步骤来实现这个想法。
- 创建一个空字符串 ans 来存储最终答案。
- 创建一个变量来计算ans字符串中比原始字符串多出来的字母。
- 循环运行到操作数(Q)的次数。
- 对于每一个 替换,将原始字符串中的子串添加到答案字符串中,使得该子串还不是答案字符串的一部分,并且该子串在原始字符串的第 索引处结束。
- 如果可以替换的话,就用目标字符串替换源字符串,并更新添加的额外字符。
- 在完成Q替换后,按原样添加原始字符串的剩余部分。
下面是上述方法的实现。
C++
// C++ code to implement the approach
#include <bits/stdc++.h>
using namespace std;
// Function to find and Replace in String
string findAndReplace(string S, int Q, int index[],
string sources[], string targets[])
{
string ans;
int space = 0;
for (int i = 0; i < Q; i++) {
// Add the substring from the original string
// to the answer string
ans += S.substr(ans.size() - space,
index[i] - ans.size() + space);
// Check if given condition satisfies or not
if (S.substr(index[i], sources[i].size())
== sources[i]) {
// Substitute the source with the target
space += targets[i].size() - sources[i].size();
// Add extra space in the space variable
ans += targets[i];
}
}
ans += S.substr(ans.size() - space);
return ans;
}
// Driver code
int main()
{
string S;
S = "gforks";
int Q = 2;
int index[] = { 0, 4 };
string sources[] = { "g", "ks" };
string targets[] = { "geeks", "geeks" };
// Function call
cout << findAndReplace(S, Q, index, sources, targets);
return 0;
}
输出
geeksforgeeks
时间复杂度。 O(|S| * Q)
辅助空间。 O(Q)