forked from prakashshuklahub/Interview-Questions
-
Notifications
You must be signed in to change notification settings - Fork 0
/
44 Wildcard Matching
61 lines (44 loc) · 1.7 KB
/
44 Wildcard Matching
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
Given an input string (s) and a pattern (p), implement wildcard pattern matching with support for '?' and '*'.
'?' Matches any single character.
'*' Matches any sequence of characters (including the empty sequence).
The matching should cover the entire input string (not partial).
Note:
s could be empty and contains only lowercase letters a-z.
p could be empty and contains only lowercase letters a-z, and characters like ? or *.
Example 1:
Input:
s = "aa"
p = "a"
Output: false
Explanation: "a" does not match the entire string "aa".
class Solution {
public boolean isMatch(String s, String p) {
boolean[][] dp = new boolean[s.length()+1][p.length()+1];
dp[0][0] = true;
char[] string = new char[s.length()+1];
char[] pattern = new char[p.length()+1];
string[0] = (char)0;
pattern[0] = (char)0;
for(int i=0;i<s.length();i++){
string[i+1] = s.charAt(i);
}
for(int i=0;i<p.length();i++){
pattern[i+1] = p.charAt(i);
}
for(int i=1;i<pattern.length;i++){
if(pattern[i]=='*' && dp[0][i-1]==true){
dp[0][i] =true;
}
}
for(int i=1;i<string.length;i++){
for(int j=1;j<pattern.length;j++){
if(string[i]==pattern[j] || pattern[j]=='?'){
dp[i][j] = dp[i-1][j-1];
}else if(pattern[j]=='*'){
dp[i][j] = dp[i-1][j] || dp[i][j-1];
}
}
}
return dp[s.length()][p.length()];
}
}