DeepRest

Match Substring After Replacement

Jun 11th, 2022 (edited)
91
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 1.47 KB | None | 0 0
  1. #KMP
  2. #O(max(n, ∆))
  3. #where n = len(s)
  4. #∆ = no. of equivalent new char pairs, who have same old chars
  5. #like if mappings = [['a', '1'], ['a', 'x'], ['b', 'x'], ['b', '3']] (old -> new)
  6. #then, ∆ = 2 (['1', 'x'] and ['3', 'x'])
  7.  
  8. class Solution:
  9.     def matchReplacement(self, s: str, sub: str, mappings: List[List[str]]) -> bool:
  10.         n = len(s)
  11.         m = len(sub)
  12.        
  13.         mp = {}
  14.         for x, y in mappings:
  15.             mp.setdefault(y, set()).add(x)
  16.         mp1 = set()
  17.         for val in mp.values():
  18.             for i in val:
  19.                 for j in val:
  20.                     mp1.add((i, j))
  21.                    
  22.         mp2 = set()
  23.         for x, y in mappings:
  24.             mp2.add((x,y))
  25.        
  26.         eqCheck1 = lambda a, b: (a == b) or ((a, b) in mp1)
  27.         eqCheck2 = lambda a, b: (a == b) or ((a, b) in mp2)
  28.        
  29.         pre = [0]*(m+1)  
  30.         for i in range(1, m):
  31.             x = pre[i - 1]
  32.             while x > 0 and not eqCheck1(sub[x], sub[i]):  
  33.                 x = pre[x-1]
  34.  
  35.             if eqCheck1(sub[x], sub[i]):
  36.                 pre[i] = x + 1
  37.        
  38.         x = 0 #already matched
  39.         for i in range(n):
  40.             while x > 0 and not eqCheck2(sub[x], s[i]):
  41.                 x = pre[x-1]  
  42.            
  43.             if eqCheck2(sub[x], s[i]):
  44.                 x += 1  
  45.                
  46.             if x == m:
  47.                 return True
  48.        
  49.         return False
  50.                
Add Comment
Please, Sign In to add comment