LeetCode 142 Regular Expression Matching

Implement regular expression matching with support for '.' and '*'.

'.' Matches any single character.
'*' Matches zero or more of the preceding element.

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", "a*") → true
isMatch("aa", ".*") → true
isMatch("ab", ".*") → true
isMatch("aab", "c*a*b") → true
分析:

參考這裏,藉助於遞歸,遞歸之前,要判斷有幾種情況。

有兩種情況,

1,p的第二位是*,則p的第一位可以和s的前i位相等,再遞歸地匹配剩餘;

2,p的第二位不是*,則p的第一位一定和s的第一位相等,再遞歸地匹配剩餘;

上面的相等包括p中是 . 和s中任意字符匹配的情況。

public class Solution {
    public boolean isMatch(String s, String p) {
        
        if(p.length()==0)
            return s.length()==0;
        //p的第二位不是*
        if(p.length()==1 || p.charAt(1) != '*'){
            if(s.length()<1 || (p.charAt(0)!='.' && s.charAt(0)!=p.charAt(0)))
                return false;
            //那麼需要第一位要相等(相等包括.匹配任意的情況),再匹配剩餘
            return isMatch(s.substring(1), p.substring(1));
        }else{//p的第二位是*,則可以匹配前i個
            int len=s.length();
            int i=-1;
            //i<0是匹配0個,.可以匹配任意
            while(i<len && (i<0 || p.charAt(0)=='.' || p.charAt(0)==s.charAt(i))){
                if(isMatch(s.substring(i+1), p.substring(2)))
                    return true;
                i++;
            }
            return false;
        }
    }
}


發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章