# 833.Find And Replace in String

**833.Find And Replace in String**

> 对于某些字符串 S，我们将执行一些替换操作，用新的字母组替换原有的字母组（不一定大小相同）。 每个替换操作具有 3 个参数：起始索引 i，源字 x 和目标字 y。规则是如果 x 从原始字符串 S 中的位置 i 开始，那么我们将用 y 替换出现的 x。如果没有，我们什么都不做。 举个例子，如果我们有 S = “abcd” 并且我们有一些替换操作 i = 2，x = “cd”，y = “ffff”，那么因为 “cd” 从原始字符串 S 中的位置 2 开始，我们将用 “ffff” 替换它。 再来看 S = “abcd” 上的另一个例子，如果我们有替换操作 i = 0，x = “ab”，y = “eee”，以及另一个替换操作 i = 2，x = “ec”，y = “ffff”，那么第二个操作将不执行任何操作，因为原始字符串中 S\[2] = 'c'，与 x\[0] = 'e' 不匹配。 所有这些操作同时发生。保证在替换时不会有任何重叠： S = "abc", indexes = \[0, 1], sources = \["ab","bc"] 不是有效的测试用例。

* 示例 1：

```
输入：S = "abcd", indexes = [0,2], sources = ["a","cd"], targets = ["eee","ffff"]
输出："eeebffff"
解释：
"a" 从 S 中的索引 0 开始，所以它被替换为 "eee"。
"cd" 从 S 中的索引 2 开始，所以它被替换为 "ffff"。
```

* 示例 2：

```
输入：S = "abcd", indexes = [0,2], sources = ["ab","ec"], targets = ["eee","ffff"]
输出："eeecd"
解释：
"ab" 从 S 中的索引 0 开始，所以它被替换为 "eee"。
"ec" 没有从原始的 S 中的索引 2 开始，所以它没有被替换。
```

* 提示：

```
0 <= indexes.length = sources.length = targets.length <= 100
0 < indexes[i] < S.length <= 1000
给定输入中的所有字符都是小写字母。
```

方法：

1. 由于字符串长度有限，因此从起始位置开始遍历，判断该索引位置是否在替换的索引数组中。并创建一个空字符串temp存储结果。
2. 如果在列表中，则判断子字符串是否相等，如果相等，则temp中加入目标字符串，并将原字符串中索引位置向后移动被替换字符串的长度。并设立一个flag表示此时已经替换过了。
3. 内层循环结束，如果发现flag没有变化，即没有进行过替换，则temp加入当前源字符串当前索引字符，并将索引位置加1.并重置flag。
4. 返回temp。

```
class Solution {
public:
    string findReplaceString(string S, vector<int>& indexes, vector<string>& sources, vector<string>& targets) {
        int slen = S.length();
        int num=indexes.size();
        string temp;
        int flag=0;
        for(int i=0;i<slen;)
        {
            for(int j=0;j<num;j++)
            {
                if(i == indexes[j])
                {
                    if(S.substr(i,sources[j].length()) == sources[j])
                    {
                        temp += targets[j];
                        i+= sources[j].length();
                        flag=1;
                    }

                }

            }
            if(!flag)
            {
                temp += S[i];
                i++;
        }
            flag=0;
        }
        return temp;

    }
};
```


---

# Agent Instructions: Querying This Documentation

If you need additional information that is not directly available in this page, you can query the documentation dynamically by asking a question.

Perform an HTTP GET request on the current page URL with the `ask` query parameter:

```
GET https://dfine.gitbook.io/leetcode/833.find_and_replace_in_string.md?ask=<question>
```

The question should be specific, self-contained, and written in natural language.
The response will contain a direct answer to the question and relevant excerpts and sources from the documentation.

Use this mechanism when the answer is not explicitly present in the current page, you need clarification or additional context, or you want to retrieve related documentation sections.
