【线性 dp】A016_LC_通配符匹配(分类讨论)

一、Problem

Given an input string (s) and a pattern §, 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 *.

Input:
s = "adceb"
p = "*a*b"
Output: true
Explanation: The first '*' matches the empty sequence, while the second '*' matches the substring "dce".

Input:
s = "acdcb"
p = "a*c?b"
Output: false

二、Solution

方法一:dp

经典串匹配,只不过加了几个约束条件…

  • 定义状态
    • f[i][j]f[i][j] 表示 s 的前 ii 个字符能否用 p 的前 jj 个字符进行匹配,这样比较好理解
  • 思考初始化:
    • f[0][0]=truef[0][0] = true
    • f[0][j]=(f[0][j1] and p[j1]==)f[0][j] = (f[0][j-1]\ and\ p[j-1] == *),当 s 为空串时,p 的前 jj 个字符只有是 * 号时,才能用 p 进行匹配;? 不行是因为 ? 只能匹配单个字符
  • 思考状态转移方程
    • 如果 s[i]=p[j]s[i] = p[j] 或者 s[i]p[j]s[i] \not= p[j]p[j]= ?p[j] =\ ?,则有 f[i][j]=f[i1][j1]f[i][j] = f[i-1][j-1]
    • 如果 s[i]p[j]p[j]=s[i] \not= p[j],p[j] = * ,则 * 有两种作用:
      • 当做空串进行匹配(ac, ac*),f[i][j]=f[i][j1]f[i][j] = f[i][j-1]
      • 当做有意义的字符串(acac, ac*),由上可得,因为 f[3][3]=truef[3][3] = true,所以 f[i][j]=f[i1][j]f[i][j] = f[i-1][j]
      • 综上,f[i][j]=f[i][j1]  f[i1][j]f[i][j] = f[i][j-1]\ ||\ f[i-1][j]
  • 思考输出f[n][m]f[n][m]
class Solution {
public:
    bool isMatch(string s, string p) {
    	int n = s.size(), m = p.size();
        vector<vector<bool>> f(n+1, vector<bool>(m+1));  f[0][0] = true;
        for (int j = 1; j <= m; j++) if (p[j-1] == '*') {
        	f[0][j] = f[0][j-1];
		}
		
        for (int i = 1; i <= n; i++)
    	for (int j = 1; j <= m; j++) {
    		if (s[i-1] == p[j-1] || p[j-1] == '?') {
    			f[i][j] = f[i-1][j-1];
    		} else if (p[j-1] == '*') {
    			f[i][j] = f[i][j-1] || f[i-1][j];
    		}
    	}
    	return f[n][m];
    }
};

复杂度分析

  • 时间复杂度:O(n×m)O(n × m)
  • 空间复杂度:O(n×m)O(n × m)
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章