Wildcard Matching
Problem link
Given an input string (s) and a pattern (p), implement wildcard pattern matching with support for '?' and '*'.
The matching should cover the entire input string (not partial).
Note:
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 :
Input:
s = "aa"
p = "a"
Output: false
Explanation: "a" does not match the entire string "aa".
Input:
s = "aa"
p = "*"
Output: true
Explanation: '*' matches any sequence.
Discussion :
public boolean isMatch(String s, String p) { int m = s.length(), n = p.length(); char[] ws = s.toCharArray(); char[] wp = p.toCharArray(); boolean[][] dp = new boolean[m+1][n+1]; dp[0][0] = true; for (int j = 1; j <= n; j++) if(wp[j-1] == '*') dp[0][j] = dp[0][j-1]; for (int i = 1; i <= m; i++) dp[i][0] = false; for (int i = 1; i <= m; i++) { for (int j = 1; j <= n; j++) { if (wp[j-1] == '*') dp[i][j] = dp[i-1][j] || dp[i][j-1]; else if (wp[j-1] == '?' || ws[i-1] == wp[j-1]) dp[i][j] = dp[i-1][j-1]; } } return dp[m][n]; }
Comments
Post a Comment