Match Substring After Replacement — LeetCode 2301 Python Solution
- Problem
- #2301
- Pattern
- Hash Map
- Reading time
- 2 min
- Source
- leetcode.com
The problem
You are given two strings s and sub. You are also given a 2D character array mappings where mappings[i] = [oldi, newi] indicates that you may perform the following operation any number of times: Replace a character oldi of sub with newi.
Example
- 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'.
Python solution
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 FalseComplexity
| Measure | Complexity |
|---|---|
| Time | O(m \times n) |
| Space | O(C^2) auxiliary |
Pattern: Hash Map
Trade memory for time: remember what you have seen so the second pass never happens. LeetCode 2301. Match Substring After Replacement is filed here on both counts: the reference solution below belongs to the algorithm family this hub collects, and LeetCode tags it Hash Table.
The hash map guide has the Python template for the pattern and the 709 LeetCode problems that use it.
Related problems
Frequently asked questions
- How hard is LeetCode 2301. Match Substring After Replacement?
- LeetCode 2301. Match Substring After Replacement is rated Hard on LeetCode.
- What is the time complexity of LeetCode 2301. Match Substring After Replacement?
- The Python solution on this page runs in O(m \times n).
- What is the space complexity of LeetCode 2301. Match Substring After Replacement?
- The Python solution on this page uses O(C^2) auxiliary space.
- What topics does LeetCode 2301. Match Substring After Replacement cover?
- LeetCode 2301. Match Substring After Replacement is tagged Array, Hash Table, String and String Matching on LeetCode.