[LeetCode] Regular Expression Matching

来源:互联网 发布:淘宝劳保用品 编辑:程序博客网 时间:2024/06/07 05:45

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


代码如下:

public class Solution {     public boolean isMatch(String s, String p) { return isMatch(s,0,p,0); } public boolean isMatch(String s,int i,String p,int j){ if(j==p.length()) return i==s.length(); if(j==p.length()-1||p.charAt(j+1)!='*'){ if(i==s.length()) return false; if(compare(s.charAt(i),p.charAt(j))){ return isMatch(s,i+1,p,j+1); } return false; } else if(p.charAt(j+1)=='*'){if(isMatch(s,i,p,j+2)) return true;for(;i<s.length();i++){if(compare(s.charAt(i),p.charAt(j))){if(isMatch(s,i+1,p,j+2)) return true;}else break;}return false; } return false; } public boolean compare(char a,char b){ return a=='.'||b=='.'||a==b; }}


原创粉丝点击