Leetcode Regular Expression Matching

来源:互联网 发布:java编写软件 编辑:程序博客网 时间:2024/06/16 12:33

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") → falseisMatch("aa","aa") → trueisMatch("aaa","aa") → falseisMatch("aa", "a*") → trueisMatch("aa", ".*") → trueisMatch("ab", ".*") → trueisMatch("aab", "c*a*b") → true

Difficulty: hard


public class Solution {        public boolean helper(String s, int s_index, String p, int p_index){        if(p.length() == p_index){            return (s.length() == s_index);        }                else if(p.length() == p_index + 1){            if(s.length() == s_index){                return false;            }            else if(s.length() == s_index + 1){                if(p.charAt(p_index) == '.' || p.charAt(p_index) == s.charAt(s_index)){                    return true;                }                return false;            }            else{                return false;            }        }                else{            if(p.charAt(p_index + 1) == '*'){                if(helper(s, s_index, p, p_index + 2)){                       return true;                }                                int i = s_index;                while(i < s.length() && (p.charAt(p_index) == s.charAt(i) || p.charAt(p_index) == '.')){                    if(helper(s, i + 1, p, p_index + 2))                        return true;                    i++;                }                // if(helper(s, i, p, p_index + 2))                //     return true;                return false;                            }            else{                if(s_index == s.length()){                    return false;                }                if(p.charAt(p_index) == '.' || p.charAt(p_index) == s.charAt(s_index)){                    return helper(s, s_index+1, p, p_index+1);                }                return false;            }                    }    }        public boolean isMatch(String s, String p) {        return helper(s, 0, p, 0);    }}


0 0
原创粉丝点击