[Leetcode] 42. Wildcard Matching

题目

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).

The function prototype should be:
bool isMatch(const char *s, const char *p)

Some examples:
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

频度: 3、

解题之法

class Solution {
public:
    bool isMatch(string s, string p) {
        int m = s.size(), n = p.size();
        vector<vector<bool>> dp(m + 1, vector<bool>(n + 1, false));
        dp[0][0] = true;
        for (int i = 1; i <= n; ++i) {
            if (p[i - 1] == '*') dp[0][i] = dp[0][i - 1];
        }
        for (int i = 1; i <= m; ++i) {
            for (int j = 1; j <= n; ++j) {
                if (p[j - 1] == '*') {
                    dp[i][j] = dp[i - 1][j] || dp[i][j - 1];
                } else {
                    dp[i][j] = (s[i - 1] == p[j - 1] || p[j - 1] == '?') && dp[i - 1][j - 1];
                }
            }
        }
        return dp[m][n];
    }
};
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容

  • **2014真题Directions:Read the following text. Choose the be...
    又是夜半惊坐起阅读 13,476评论 0 23
  • (本文观点纯属个人观点,并非具有权威参考价值,如有错误,望看客指出。) 简介 开发之前,首先来了解一下蓝牙BLE和...
    NikouKarter阅读 18,056评论 16 81
  • 卜算子·咏师 粉笔写春秋, 教苑皆清苦。 搭成登天揽月梯, 翰林思争俏。 桃李正芬芳, 无悔躬耕忙。 鸿鹄冲霄逐云...
    童声童话阅读 3,199评论 2 5
  • “死丫崽子,跑哪去啦?” 随着响亮的一声叫骂,从一间旧房子里走出一个30多岁的胖女人。她看上去特别精神,眼睛亮亮的...
    温暖鞍山阅读 1,644评论 0 1