ได้รับสตริง S และรายการการแทนที่: index, source, target หาก source เริ่มที่ index ใน S ต้นฉบับ ให้แทนที่ด้วย target มิฉะนั้นข้ามไป
ตัวอย่าง
Input − S="abcd", indexes=[0,2], sources=["a","cd"], targets=["eee","ffff"] Output − "eeebffff"
คำอธิบาย − index 0: "a"→"eee", index 2: "cd"→"ffff" (ใช้ S ต้นฉบับ)
แนวทางการแก้ปัญหา
- จับคู่ (index, original_index) เรียงจาก index มากไปน้อย (ท้ายไปหน้า)
- ประมวลผลจากท้ายไปหน้าเพื่อไม่ให้การแทนที่ก่อนหน้าส่งผลต่อ index ต่อไป
- ตรวจสอบ S.substr(index, source.length()) == source
- แทนที่: S = S.substr(0, index) + target + S.substr(index + source.length())
ตัวอย่างโค้ด C++
#include <bits/stdc++.h>
using namespace std;
class Solution {
public:
string findReplaceString(string S, vector& indexes, vector& sources, vector& targets) {
vector> sorted;
for (int i = 0; i < indexes.size(); i++)
sorted.push_back({indexes[i], i});
sort(sorted.rbegin(), sorted.rend()); // descending
for (auto [idx, orig] : sorted) {
string src = sources[orig], tgt = targets[orig];
if (S.substr(idx, src.size()) == src)
S = S.substr(0, idx) + tgt + S.substr(idx + src.size());
}
return S;
}
};
int main() {
vector idx = {0, 2};
vector src = {"a", "cd"}, tgt = {"eee", "ffff"};
Solution ob;
cout << ob.findReplaceString("abcd", idx, src, tgt); // eeebffff
return 0;
}
ผลลัพธ์
eeebffff
บทความนี้แก้ปัญหา Find And Replace in String (LeetCode 833) โดยประมวลผลการแทนที่จากขวาไปซ้ายเพื่อป้องกันการเปลี่ยนแปลง index ของการแทนที่ที่ยังไม่ได้ประมวลผล