3407. Substring Matching Pattern LeetCode Solution
In this guide, you will get 3407. Substring Matching Pattern LeetCode Solution with the best time and space complexity. The solution to Substring Matching Pattern problem is provided in various programming languages like C++, Java, and Python. This will be helpful for you if you are preparing for placements, hackathons, interviews, or practice purposes. The solutions provided here are very easy to follow and include detailed explanations.
Table of Contents
- Problem Statement
- Complexity Analysis
- Substring Matching Pattern solution in C++
- Substring Matching Pattern solution in Java
- Substring Matching Pattern solution in Python
- Additional Resources

Problem Statement of Substring Matching Pattern
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 <= 50
1 <= p.length <= 50
s contains only lowercase English letters.
p contains only lowercase English letters and exactly one '*'
Complexity Analysis
- Time Complexity: O(n)
- Space Complexity: O(1)
3407. Substring Matching Pattern LeetCode Solution in C++
class Solution {
public:
bool hasMatch(const string& s, const string& p) {
const int starPos = p.find('*');
const string prefix = p.substr(0, starPos);
const string suffix = p.substr(starPos + 1);
const int i = s.find(prefix);
return i != string::npos &&
s.find(suffix, i + prefix.size()) != string::npos;
}
};
/* code provided by PROGIEZ */
3407. Substring Matching Pattern LeetCode Solution in Java
class Solution {
public boolean hasMatch(String s, String p) {
final int starPos = p.indexOf('*');
final String prefix = p.substring(0, starPos);
final String suffix = p.substring(starPos + 1);
final int i = s.indexOf(prefix);
return i != -1 && s.indexOf(suffix, i + prefix.length()) != -1;
}
}
// code provided by PROGIEZ
3407. Substring Matching Pattern LeetCode Solution in Python
class Solution:
def hasMatch(self, s: str, p: str) -> bool:
prefix, suffix = p.split('*')
i = s.find(prefix)
return i != -1 and s.find(suffix, i + len(prefix)) != -1
# code by PROGIEZ
Additional Resources
- Explore all LeetCode problem solutions at Progiez here
- Explore all problems on LeetCode website here
Happy Coding! Keep following PROGIEZ for more updates and solutions.