美文网首页
10. Regular Expression Matching

10. Regular Expression Matching

作者: HalcyonMoon | 来源:发表于2016-06-28 22:45 被阅读0次

    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

    public class Solution {
        public boolean isMatch(char []s, int sIndex, char[] p, int pIndex){
            int sLen = s.length;
            int pLen = p.length;
            
            if(sIndex == sLen && pIndex == pLen){
                return true;
            }else if(sIndex != sLen && pIndex == pLen){
                return false;
            }
            
            //else pIndex != pLen
            if(pIndex+1 < pLen && p[pIndex + 1] == '*'){
                if(sIndex == sLen){
                    return isMatch(s, sIndex, p, pIndex+2);
                }
                if(p[pIndex] == '.'){
                    if(isMatch(s, sIndex+1, p, pIndex)){
                        return true;
                    }else{
                        return isMatch(s, sIndex, p, pIndex+2);
                    }
                }else{
                    if(s[sIndex] == p[pIndex]){
                        if(isMatch(s, sIndex+1, p, pIndex)){
                            return true;
                        }else{
                            return isMatch(s, sIndex, p, pIndex+2);
                        }
                    }else{
                        return isMatch(s, sIndex, p, pIndex+2);
                    }
                }
            }else{
                if(sIndex < sLen && (p[pIndex] == '.' || p[pIndex] == s[sIndex])){
                    return isMatch(s, sIndex+1, p, pIndex+1);
                }else{
                    return false;
                }
            }
        }
        
        public boolean isMatch(String s, String p) {
            char [] sc = s.toCharArray();
            char [] pc = p.toCharArray();
    
            return isMatch(sc, 0, pc, 0);
        }
    }
    

    相关文章

      网友评论

          本文标题:10. Regular Expression Matching

          本文链接:https://www.haomeiwen.com/subject/rmgtjttx.html