标签:
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
SOLUTION:
通配符匹配,很像Distinct Subsequences的思维方式。像这样给俩字串,然后看true or false的,基本DP可以用。既然给了俩字传,那就先不考虑优化问题,先开个二维空间记录结果。
状态:f(i , j) 表示S前i个跟T前j个可以不可以匹配。
方程:情况1. T(j) == ? || T(j) == S(i) (因为这两种情况都是匹配一个字符,所以放在一起)这时候 f(i, j) = f(i - 1, j - 1)。就是说T(j)必须去匹配,不然这个字母没意义了。
情况2. T(j) == *,这时候*匹配任意字符,所以呢,f(i, j ) =f(i, j - 1) || f(i - 1, j - 1) || f(i - 2, j - 1) || f(i - 3, j - 1) ... ... || f(1, j - 1):意思就是说,S(i) 之前包括S(i)本身,只要有任意一个跟T(*)前面的一个字符匹配上,就可以。
看起来很麻烦,但是,仔细看,这个公式可以简化:因为f(i - 1, j) = f(i - 1, j - 1) || f(i - 2, j - 1) || ... ... || f(1, j - 1), 所以上面f(i , j) = f(i , j - 1) || f ( i - 1, j) 。
通俗的说,就是,在当时这一dp层去考虑,我可以用*匹配 f (i - 1, j) ,也可以不用*去匹配 f (i, j - 1)。
初始化:f(0, 0 )用方程推不出,所以要单独考虑。 f(0,0) = true 意思就是null匹配null。
代码如下:
public class Solution { /** * @param s: A string * @param p: A string includes "?" and "*" * @return: A boolean */ // f(i, j) if p(j) = ? || p(j) == s(i) ==>f(i,j) = f(i - 1, j - 1) // if p(j) = * ==> f(i,j) = f(i - 1, j) f(i, j - 1) public boolean isMatch(String s, String p) { if (s == null){ return p == null; } if (p == null){ return s == null; } boolean[][] result = new boolean[s.length() + 1][p.length() + 1]; result[0][0] = true; for (int i = 1; i <= s.length(); i++){ for (int j = 1; j <= p.length(); j++){ if (result[0][j - 1] && p.charAt(j - 1) == ‘*‘){ result[0][j] = true; } if (p.charAt(j - 1) == s.charAt(i - 1) || p.charAt(j - 1) == ‘?‘){ result[i][j] = result[i - 1][j - 1]; } if (p.charAt(j - 1) == ‘*‘){ result[i][j] = (result[i - 1][j] || result[i][j - 1]); } } } return result[s.length()][p.length()]; } }
标签:
原文地址:http://www.cnblogs.com/tritritri/p/4957759.html