044 Wildcard Matching

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

Example:

Input:
s = "aa"
p = "a"
Output: false
Explanation: "a" does not match the entire string "aa".

Input:
s = "aa"
p = "*"
Output: true
Explanation: ' * ' matches any sequence.

Input:
s = "cb"
p = "?a"
Output: false
Explanation: '?' matches 'c', but the second letter is 'a', which does not match 'b'.

Input:
s = "adceb"
p = "ab"
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

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

解释下题目:

自己实现通配符。

1. 二维矩阵判断法,从这里借鉴的

实际耗时:59ms

public boolean isMatch(String s, String p) {
        boolean[][] match = new boolean[s.length() + 1][p.length() + 1];
        match[s.length()][p.length()] = true;
        for (int i = p.length() - 1; i >= 0; i--) {
            if (p.charAt(i) != '*')
                break;
            else
                match[s.length()][i] = true;
        }
        for (int i = s.length() - 1; i >= 0; i--) {
            for (int j = p.length() - 1; j >= 0; j--) {
                if (s.charAt(i) == p.charAt(j) || p.charAt(j) == '?')
                    match[i][j] = match[i + 1][j + 1];
                else if (p.charAt(j) == '*')
                    match[i][j] = match[i + 1][j] || match[i][j + 1];
                else
                    match[i][j] = false;
            }
        }
        return match[0][0];
    }

  思路就是默认是匹配的,然后两个从最后开始匹配,简单说就是目前匹配与否,取决于之前是否匹配,如果匹配那么判断当前是否匹配,如果匹配则“继承”之前的状态,如果不匹配则直接false

时间复杂度O(n*m)
空间复杂度O(n*m)

©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

相关阅读更多精彩内容

  • rljs by sennchi Timeline of History Part One The Cognitiv...
    sennchi阅读 12,196评论 0 10
  • 麦隆咖啡 弘基时尚店 终于拔了这根心头草,一杯甜心雨,与其说来喝咖啡,不如说来发呆玩,看美式咖啡的热气氤氲,棉花糖...
    柯小云阅读 1,850评论 2 3
  • 呼啸而来的寒风,忠实履行着,对秋凉的执着向往, 瞬间席卷了,肆虐多日的阴霾, 让空气中的污浊,在刺骨的颤抖中,放弃...
    文风起武阅读 3,184评论 2 11
  • 虽然从小生长在西北一带,少许海鲜的餐饮,自从来到南方以后,还是比较喜欢吃海鲜的,因虾过敏,其它都放弃了,唯独对于吃...
    会飞的鱼Nicole阅读 2,854评论 0 2
  • 珠帘欲卷相思恼,试问谁知晓。 玉栏寒漏浸衣襟,梦你银河凝泪结冰心。 花前诺许今犹记,望月人千里。 怨郎何不早归来,...
    刘小地阅读 3,523评论 16 24

友情链接更多精彩内容