Physical Address
304 North Cardinal St.
Dorchester Center, MA 02124
Given an input string (s
) and a pattern (p
), implement wildcard pattern matching with support for '?'
and '*'
where:
'?'
Matches any single character.'*'
Matches any sequence of characters (including the empty sequence).The matching should cover the entire input string (not partial).
Example 1:
Input: s = "aa", p = "a"
Output: false
Explanation: "a" does not match the entire string "aa".
Example 2:
Input: s = "aa", p = "*"
Output: true
Explanation: '*' matches any sequence.
Example 3:
Input: s = "cb", p = "?a"
Output: false
Explanation: '?' matches 'c', but the second letter is 'a', which does not match 'b'.
Constraints:
0 <= s.length, p.length <= 2000
s
contains only lowercase English letters.p
contains only lowercase English letters, '?'
or '*'
.public class Solution {
public boolean isMatch(String s, String p) {
boolean[][] match=new boolean[s.length()+1][p.length()+1];
match[s.length()][p.length()]=true;
for(int i=p.length()-1;i>=0;i--){
if(p.charAt(i)!='*')
break;
else
match[s.length()][i]=true;
}
for(int i=s.length()-1;i>=0;i--){
for(int j=p.length()-1;j>=0;j--){
if(s.charAt(i)==p.charAt(j)||p.charAt(j)=='?')
match[i][j]=match[i+1][j+1];
else if(p.charAt(j)=='*')
match[i][j]=match[i+1][j]||match[i][j+1];
else
match[i][j]=false;
}
}
return match[0][0];
}
}
class Solution {
public:
bool isMatch(string s, string p) {
int m = s.length(), n = p.length();
if (n > 30000) return false; // the trick
vector<bool> cur(m + 1, false);
cur[0] = true;
for (int j = 1; j <= n; j++) {
bool pre = cur[0]; // use the value before update
cur[0] = cur[0] && p[j - 1] == '*';
for (int i = 1; i <= m; i++) {
bool temp = cur[i]; // record the value before update
if (p[j - 1] != '*')
cur[i] = pre && (s[i - 1] == p[j - 1] || p[j - 1] == '?');
else cur[i] = cur[i - 1] || cur[i];
pre = temp;
}
}
return cur[m];
}
};
class Solution:
def isMatch(self, s, p):
dp = [[False for _ in range(len(p)+1)] for i in range(len(s)+1)]
dp[0][0] = True
for j in range(1, len(p)+1):
if p[j-1] != '*':
break
dp[0][j] = True
for i in range(1, len(s)+1):
for j in range(1, len(p)+1):
if p[j-1] in {s[i-1], '?'}:
dp[i][j] = dp[i-1][j-1]
elif p[j-1] == '*':
dp[i][j] = dp[i-1][j] or dp[i][j-1]
return dp[-1][-1]
In our experience, we suggest you solve this Wildcard Matching LeetCode Solution and gain some new skills from Professionals completely free and we assure you will be worth it.
If you are stuck anywhere between any coding problem, just visit Queslers to get the Wildcard Matching LeetCode Solution
I hope this Wildcard Matching LeetCode Solution would be useful for you to learn something new from this problem. If it helped you then don’t forget to bookmark our site for more Coding Solutions.
This Problem is intended for audiences of all experiences who are interested in learning about Data Science in a business context; there are no prerequisites.
Keep Learning!
More Coding Solutions >>