个人记录-LeetCode 44. Wildcard Matching

来源:互联网 发布:高中化学知识网络结构 编辑:程序博客网 时间:2024/06/02 09:52

问题:
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") → falseisMatch("aa","aa") → trueisMatch("aaa","aa") → falseisMatch("aa", "*") → trueisMatch("aa", "a*") → trueisMatch("ab", "?*") → trueisMatch("aab", "c*a*b") → false

这里唯一需要额外说明的是:问题要求的是完全匹配。
举例中的最后一项,“aab”仅为正则表达式“c*a*b”对应字符串的子串,因此结果还是false。

代码示例:
思路:
?号的处理比较简单,主要还是需要考虑如何处理*。

由于*可以替代0~任意多个字符,因此对应的匹配规则可以抽象成下图:

public class Solution {    public boolean isMatch(String s, String p) {        if (s == null || p ==null) {            return false;        }        if (s.length() < 1) {            return p.length() < 1 || p.equals("*");        }        int sIndex = 0, pIndex = 0;        boolean hasStar = false;        //用于保存*后的第一个字符的位置        int afterStarIndexInP = -1;        //用于保存与*匹配时,s中字符的位置        int starIndexInS = -1;        while (sIndex < s.length()) {            //完全相等时,s和p的下标同时增加            if (pIndex <= p.length() - 1 &&                    (s.charAt(sIndex) == p.charAt(pIndex) || p.charAt(pIndex) == '?')) {                ++sIndex;                ++pIndex;                continue;            }            //不相等,但碰到*号时            if (pIndex <= p.length() - 1 && p.charAt(pIndex) == '*') {                hasStar = true;                if (pIndex < p.length() - 1) {                    ++pIndex;                } else {                    //*是最后正则字符串的最后一个位置,前面全部匹配了,那么结果一定就是成功的                    return true;                }                //记录*后,第一个字符的位置                afterStarIndexInP = pIndex;                //记录此时s中字符的位置,注意到sIndex并没有增加,                //此时,就是假设*代表0个字符                starIndexInS = sIndex;                continue;            }            //不匹配,但之前遇到过*            if (hasStar) {                //pIndex重新回到*后的第一个位置                pIndex = afterStarIndexInP;                //增加startIndexInS的值                //即逐渐增加*代表的字符数量                sIndex = ++starIndexInS;                continue;            }            //不匹配且无*,返回false            return false;        }        //若正则表达式还有剩余长度,那么必须全为*,才是true        //例如“abcd”和“abcd***”返回的true        //但“abcd”和“abcd**e”返回的就是false        while (pIndex < p.length()) {            if (p.charAt(pIndex) != '*') {                return false;            }            ++pIndex;        }        return true;    }}
0 0
原创粉丝点击