Guest User

code

a guest
Jul 26th, 2024
615
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 1.00 KB | None | 0 0
  1. def solve(string, regex):
  2.    
  3.     left_regex, right_regex = regex.split("*")
  4.  
  5.     left = right = -1
  6.  
  7.     for idx in range(len(string)):
  8.         i = 0
  9.         ptr = idx
  10.  
  11.         while i < len(left_regex) and ptr < len(string) and string[ptr] == left_regex[i]:
  12.             ptr += 1
  13.             i += 1
  14.        
  15.         if i == len(left_regex): # matched left regex
  16.             left = idx
  17.             break
  18.    
  19.  
  20.     for idx in range(len(string) - 1, -1, -1):
  21.         i = len(right_regex) - 1
  22.         ptr = idx
  23.  
  24.         while i >= 0 and ptr > left and string[ptr] == right_regex[i]:
  25.             ptr -= 1
  26.             i -= 1
  27.                
  28.         if i == -1: # matched right regex
  29.             right = idx
  30.             break
  31.    
  32.     if -1 in (left, right):
  33.         return -1
  34.    
  35.     return right - left + 1
  36.  
  37.  
  38. def main():
  39.     tc = [("abcmnobcd", "abc*bcd"), ("abc", "a*"), ("abcd", "a*e")]
  40.  
  41.     for string, regex in tc:
  42.         result = solve(string, regex)
  43.         print(result)
  44.  
  45. main()
Advertisement
Add Comment
Please, Sign In to add comment