C++字符串查找和替换


假设我们有一个字符串S,我们将执行一些替换操作,用新的字符替换字符组。在每个替换操作中,有3个参数:起始索引i、源单词x和目标单词y。规则是:如果x从原始字符串S的i位置开始,则我们将该x替换为y;否则,什么也不做。

例如,如果我们有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 = “abcd”,indices = [0,2],sources = [“a”, “cd”],targets = [“eee”, “ffff”],则输出将是“eeebffff”。这是因为"a"从S的第0位开始,所以它被替换为"eee"。现在"cd"从S的第2位开始,所以它被替换为"ffff"。

为了解决这个问题,我们将遵循以下步骤:

  • 定义一个名为sorted的键值对数组,n := indexes数组的大小
  • 对于i从0到n – 1
    • 将键值对(indexes[i], i)插入到sorted中。
  • 将sorted按逆序排序
  • 对于j从0到n – 1
    • i := sorted[j]键值对的第一个值
    • src := sources[sorted[j]键值对的第二个值]
    • target := targets[sorted[j]键值对的第二个值]
    • 如果S从索引i到sources大小-1的子串与source相同,则
      • S := (S从索引0到i的子串)连接target,连接(S从i到sources大小-1的子串)
  • 返回S

让我们来看下面的实现,以便更好地理解:

示例

 在线演示

#include <bits/stdc++.h>
using namespace std;
class Solution {
public:
   string findReplaceString(string S, vector<int>& indexes, vector<string>& sources,       vector<string>& targets) {
      vector < pair <int, int> > sorted;
      int n = indexes.size();
      for(int i = 0; i < n; i++){
         sorted.push_back({indexes[i], i});
      }
      sort(sorted.rbegin(), sorted.rend());
      for(int j = 0; j < n; j++){
         int i = sorted[j].first;
         string source = sources[sorted[j].second];
         string target = targets[sorted[j].second];
         if(S.substr(i, source.size()) == source){
            S = S.substr(0, i) + target + S.substr(i + source.size());
         }
      }
      return S;
   }
};
main(){
   vector<int> v1 = {0, 2};
   vector<string> v2 = {"a", "cd"};
   vector<string> v3 = {"eee", "ffff"};
   Solution ob;
   cout << (ob.findReplaceString("abcd", v1, v2, v3));
}

输入

"abcd"
[0, 2]
["a", "cd"]
["eee", "ffff"]

输出

eeebffff

更新于:2020年5月5日

浏览量1K+

开启你的职业生涯

完成课程获得认证

开始学习
广告
© . All rights reserved.