📅  最后修改于: 2023-12-03 14:43:52.365000             🧑  作者: Mango
Leetcode 809 is a coding problem on the Leetcode platform that challenges programmers to solve a string manipulation task. In this problem, you are given a string input consisting of words separated by spaces. Your task is to find and replace specific characters in all words according to a given mapping.
Given a string source
and a mapping target
, each key in target
is an English lowercase letter, and each value is a string with length 1. Replace all occurrences of characters in source
with the corresponding characters in target
.
The replacement must be made in the order of characters in source
. If the replacements in source
overlap, you need to choose the longest possible replacement sequence. If there is a tie, replace the leftmost character first. After the replacements are done, return the resulting transformed string.
It is guaranteed that for each character in source
, there is a corresponding character in target
with the same length.
source = "abcd"
target = ["a", "b", "cd", "xyz"]
"xycdz"
To solve this problem, we can iterate through the words in the source
string and replace each occurrence of the characters based on the given mapping provided in target
. Since we need to choose the longest possible replacement sequence and prefer the leftmost character when there is a tie, we can start by iterating through the characters in source
and checking if any substring starting from that character matches any of the keys in the target
mapping. If a match is found, we replace the substring with the corresponding value in target
and continue iterating.
result
to store the transformed string.c
in source
:curr
to store the current substring.next_c
starting from c
:next_c
to curr
.curr
is found in target
as a key, replace curr
with the corresponding value and break the loop.curr
(either replaced or original) to result
.result
as the transformed string.The time complexity for this approach is O(n*m), where n is the length of source
and m is the total number of characters in target
. The space complexity is O(n), which is needed to store the transformed string result
.
def findReplaceString(source: str, indexes: List[int], sources: List[str], targets: List[str]) -> str:
result = ''
n = len(source)
changes = {}
for i in range(len(indexes)):
if source[indexes[i]:indexes[i]+len(sources[i])] == sources[i]:
changes[indexes[i]] = targets[i]
i = 0
while i < n:
if i in changes:
result += changes[i]
i += len(sources[i])
else:
result += source[i]
i += 1
return result