|
| 1 | +package com.fishercoder.solutions; |
| 2 | + |
| 3 | +/** |
| 4 | + * 44. Wildcard Matching |
| 5 | + * Implement wildcard pattern matching with support for '?' and '*'. |
| 6 | +
|
| 7 | + '?' Matches any single character. |
| 8 | + '*' Matches any sequence of characters (including the empty sequence). |
| 9 | +
|
| 10 | + The matching should cover the entire input string (not partial). |
| 11 | +
|
| 12 | + The function prototype should be: |
| 13 | + bool isMatch(const char *s, const char *p) |
| 14 | +
|
| 15 | + Some examples: |
| 16 | + isMatch("aa","a") → false |
| 17 | + isMatch("aa","aa") → true |
| 18 | + isMatch("aaa","aa") → false |
| 19 | + isMatch("aa", "*
EEA6
") → true |
| 20 | + isMatch("aa", "a*") → true |
| 21 | + isMatch("ab", "?*") → true |
| 22 | + isMatch("aab", "c*a*b") → false |
| 23 | + */ |
| 24 | +public class _44 { |
| 25 | + |
| 26 | + public boolean isMatch(String s, String p) { |
| 27 | + boolean[][] match = new boolean[s.length()+1][p.length()+1]; |
| 28 | + match[s.length()][p.length()] = true; |
| 29 | + for (int i = p.length()-1; i >= 0; i--) { |
| 30 | + if (p.charAt(i) != '*') { |
| 31 | + break; |
| 32 | + } else { |
| 33 | + match[s.length()][i] = true; |
| 34 | + } |
| 35 | + } |
| 36 | + |
| 37 | + for (int i = s.length()-1; i >= 0; i--) { |
| 38 | + for (int j = p.length()-1; j >= 0; j--) { |
| 39 | + if (s.charAt(i) == p.charAt(j) || p.charAt(j) == '?') { |
| 40 | + match[i][j] = match[i+1][j+1]; |
| 41 | + } else if (p.charAt(j) == '*') { |
| 42 | + match[i][j] = match[i+1][j] || match[i][j+1]; |
| 43 | + } else { |
| 44 | + match[i][j] = false; |
| 45 | + } |
| 46 | + } |
| 47 | + } |
| 48 | + return match[0][0]; |
| 49 | + } |
| 50 | + |
| 51 | +} |
0 commit comments