Substring Matching Pattern Problem
Description
LeetCode Problem 3407.
You are given a string s and a pattern string p, where p contains exactly one '*' character.
The '*' in p can be replaced with any sequence of zero or more characters.
Return true if p can be made a substring of s, and false otherwise.
Example 1:
Input: s = "leetcode", p = "ee*e"
Output: true
Explanation:
By replacing the '*' with "tcod", the substring "eetcode" matches the pattern.
Example 2:
Input: s = "car", p = "c*v"
Output: false
Explanation:
There is no substring matching the pattern.
Example 3:
Input: s = "luck", p = "u*"
Output: true
Explanation:
The substrings "u", "uc", and "uck" match the pattern.
Constraints:
1 <= s.length <= 501 <= p.length <= 50scontains only lowercase English letters.pcontains only lowercase English letters and exactly one'*'
Solution
Approach: String Matching
The pattern contains exactly one *, which stands for any string (possibly empty). So the pattern matches a substring of s when the parts before and after the * occur in s in that order without overlapping.
Split p at * and keep a pointer i into s, starting at 0. For each part t, search for it in s from position i. If it is not found, return false; otherwise move i just past the match and continue with the next part. If every part is found, return true.
Complexity: O(nm) time, O(m) extra space, where n and m are the lengths of s and p.
class Solution:
def hasMatch(self, s: str, p: str) -> bool:
i = 0
for t in p.split("*"):
j = s.find(t, i)
if j == -1:
return False
i = j + len(t)
return True