def getLongestMatchingSubstring(text: str, regex: str) -> int:
# Step 1: Split the regex into prefix and suffix around the wildcard '*' if '*' not in regex:
return -1 # Invalid input if '*' is not present prefix, suffix = regex.split('*')
n = len(text)
longest = -1 # Start with -1 in case no valid substring is found # Step 2: Search for valid substrings in the text for i in range(n):
# Check if text starting from index i matches the prefix if text[i:i+len(prefix)] == prefix:
# Try to match the suffix after this prefix for j in range(i + len(prefix), n + 1):
# Check if text ending at j matches the suffix if text[j-len(suffix):j] == suffix:
# We have found a valid match, calculate its length current_length = j - i
longest = max(longest, current_length)
return longest
OR
def getLongestSubstring(text, regex):
# Split the regex into prefix and suffix parts parts = regex.split('*')
prefix, suffix = parts[0], parts[1]
max_len = -1 # Initialize max length to -1 (no match) # Iterate through all possible start positions in the text for i in range(len(text)):
# Check if the substring starting at i matches the prefix if text[i:i + len(prefix)] == prefix:
# Look for suffix match after the prefix for j in range(i + len(prefix), len(text) + 1):
# Check if the substring ending at j matches the suffix if text[j-len(suffix):j] == suffix:
# Calculate the total length of the matching substring total_len = j - i
max_len = max(max_len, total_len)
return max_len