Match Substring After Replacement Problem
Description
LeetCode Problem 2301.
You are given two strings s and sub. You are also given a 2D character array mappings where mappings[i] = [old_i, new_i] indicates that you may perform the following operation any number of times:
- Replace a character
old_iofsubwithnew_i.
Each character in sub cannot be replaced more than once.
Return true if it is possible to make sub a substring of s by replacing zero or more characters according to mappings. Otherwise, return false.
A substring is a contiguous non-empty sequence of characters within a string.
Example 1:
Input: s = "fool3e7bar", sub = "leet", mappings = [["e","3"],["t","7"],["t","8"]]
Output: true
Explanation: Replace the first 'e' in sub with '3' and 't' in sub with '7'.
Now sub = "l3e7" is a substring of s, so we return true.
Example 2:
Input: s = "fooleetbar", sub = "f00l", mappings = [["o","0"]]
Output: false
Explanation: The string "f00l" is not a substring of s and no replacements can be made.
Note that we cannot replace '0' with 'o'.
Example 3:
Input: s = "Fool33tbaR", sub = "leetd", mappings = [["e","3"],["t","7"],["t","8"],["d","b"],["p","b"]]
Output: true
Explanation: Replace the first and second 'e' in sub with '3' and 'd' in sub with 'b'.
Now sub = "l33tb" is a substring of s, so we return true.
Constraints:
1 <= sub.length <= s.length <= 50000 <= mappings.length <= 1000mappings[i].length == 2old_i != new_isandsubconsist of uppercase and lowercase English letters and digits.old_iandnew_iare either uppercase or lowercase English letters or digits.
Solution
Approach: Hash Table + Enumeration
Store, for each character, the set of characters it may be replaced with. Try every window of s with the length of sub; a window matches when each character equals the one in sub or is in the allowed set for that sub character. Return true on the first matching window.
Complexity: O(m * n) time, where m is the length of s and n the length of sub; the table is at most C^2 entries for a character set of size C.
from collections import defaultdict
class Solution:
def matchReplacement(self, s: str, sub: str, mappings: List[List[str]]) -> bool:
d = defaultdict(set)
for a, b in mappings:
d[a].add(b)
for i in range(len(s) - len(sub) + 1):
if all(a == b or a in d[b] for a, b in zip(s[i : i + len(sub)], sub)):
return True
return False