Given a string s, a string target and a mapping from characters to their possible replacements, determine whether target can appear as a contiguous substring of s after applying allowed character replacements to s.
Each character in s can either stay as itself or be replaced by any one of its mapped replacement characters. A character that is not a key of the mapping can only match itself.
Return True if target can be found as a contiguous substring of the (possibly modified) string s, and False otherwise.
Function Signature
def can_find_substring(s: str, target: str, mapping: dict[str, list[str]]) -> bool:
Rules
-
Each key of
mapping
is a single character of
s
, and its list holds the single characters it may become. Staying unchanged is always allowed, whether or not the key lists itself.
-
Replacements apply only to characters of
s
. The characters of
target
are never changed.
-
Each position of
s
chooses independently. The same letter may become different characters at different positions.
-
Replacements are not chained. If
'a'
maps to
'b'
and
'b'
maps to
'c'
, an
'a'
still cannot become
'c'
.
Constraints
-
1 <= len(s) <= 10^5
-
1 <= len(target) <= len(s)
-
Mapping keys and values consist of lowercase English letters.
-
All characters in
s
and
target
are lowercase English letters.
Examples
Input: s = "abcdef", target = "bxd", mapping = {"c": ["x", "y"]}
Output: True
The substring "bcd" starting at index 1 can become "bxd" because 'c' may be replaced with 'x', and 'b' and 'd' already match.
Input: s = "hello", target = "world", mapping = {"h": ["w"], "e": ["o"], "l": ["r", "l"], "o": ["d"]}
Output: True
The whole string transforms with h to w, e to o, the first l to r, the second l unchanged and o to d, which produces "world".
Input: s = "xay", target = "xc", mapping = {"a": ["b"], "b": ["c"]}
Output: False
In the window "xa", the 'a' can only be 'a' or 'b', because the replacement from 'b' to 'c' cannot be chained onto it. In the window "ay", 'a' cannot become 'x'.