标签:
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).
isMatch("aa","a") → false
isMatch("aa","aa") → true
isMatch("aaa","aa") → false
isMatch("aa", "*") → true
isMatch("aa", "a*") → true
isMatch("ab", "?*") → true
isMatch("aab", "c*a*b") → false
if (p.charAt(i - 1) == s.charAt(j - 1) || p.charAt(i - 1) == ‘?‘) {
match[i][j] = match[i - 1][j - 1];
} else if (p.charAt(i - 1) == ‘*‘) {
match[i][j] = match[i - 1][j - 1] || match[i - 1][j] || match[i][j - 1];
// match[i][j - 1] 指的是用* 替换S中1个j或多个j之前的character,当然那些character可以是连续的。
}
1 public class Solution { 2 /** 3 * @param s: A string 4 * @param p: A string includes "?" and "*" 5 * @return: A boolean 6 */ 7 public boolean isMatch(String s, String p) { 8 if (s == null || p == null) 9 return false; 10 boolean[][] match = new boolean[p.length() + 1][s.length() + 1]; 11 match[0][0] = true; 12 for (int i = 1; i < match[0].length; i++) { 13 match[0][i] = false; 14 } 15 16 for (int i = 1; i < match.length; i++) { 17 if (p.charAt(i - 1) == ‘*‘) { 18 match[i][0] = match[i - 1][0]; 19 } 20 } 21 22 for (int i = 1; i < match.length; i++) { 23 for (int j = 1; j < match[0].length; j++) { 24 if (p.charAt(i - 1) == s.charAt(j - 1) || p.charAt(i - 1) == ‘?‘) { 25 match[i][j] = match[i - 1][j - 1]; 26 } else if (p.charAt(i - 1) == ‘*‘) { 27 match[i][j] = match[i - 1][j - 1] || match[i - 1][j] || match[i][j - 1]; 28 } 29 } 30 } 31 32 return match[p.length()][s.length()]; 33 } 34 }
标签:
原文地址:http://www.cnblogs.com/beiyeqingteng/p/5677739.html