Leetcode 862 Solution

This article provides solution to leetcode question 862 (find-and-replace-in-string)

https://leetcode.com/problems/find-and-replace-in-string

Solution

class Solution:
    def findReplaceString(self, s: str, indices: List[int], sources: List[str], targets: List[str]) -> str:
        ans = ""

        d = list(zip(indices, sources, targets))
        d.sort()
        j = 0
        i = 0

        while i < len(s):
            if j < len(d) and d[j][0] == i:
                index = d[j][0]
                source = d[j][1]
                target = d[j][2]
                j += 1

                if s[i:i + len(source)] == source:
                    ans += target
                    i += len(source)
                    continue

            ans += s[i]
            i += 1

        return ans