3407. Substring Matching Pattern
Description
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'*'
Solutions
Solution 1: String Matching
According to the problem description, * can be replaced by any sequence of zero or more characters, so we can split the pattern string \(p\) by * into several substrings. If these substrings appear in order in the string \(s\), then \(p\) can become a substring of \(s\).
Therefore, we first initialize a pointer \(i\) to the start of string \(s\), then iterate over each substring \(t\) obtained by splitting the pattern string \(p\) by *. For each \(t\), we search for it in \(s\) starting from position \(i\). If it is found, we move the pointer \(i\) to the end of \(t\) and continue searching for the next substring. If it is not found, it means the pattern string \(p\) cannot become a substring of \(s\), and we return \(\text{false}\). If all substrings are found, we return \(\text{true}\).
The time complexity is \(O(n \times m)\), and the space complexity is \(O(m)\), where \(n\) and \(m\) are the lengths of strings \(s\) and \(p\), respectively.
1 2 3 4 5 6 7 8 9 | |
1 2 3 4 5 6 7 8 9 10 11 12 13 | |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 | |
1 2 3 4 5 6 7 8 9 10 11 | |
1 2 3 4 5 6 7 8 9 10 11 | |
1 2 3 4 5 6 7 8 9 10 11 12 13 | |