首页 > 其他 > 详细

Regular Expression Matching

时间:2014-10-04 04:23:26      阅读:386      评论:0      收藏:0      [点我收藏+]

‘.’ 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

bubuko.com,布布扣

      bubuko.com,布布扣

 

用dfa 来帮助分析.

 

 

/*exhaustive search 

http://leetcode.com/2011/09/regular-expression-matching.html
http://blog.csdn.net/fightforyourdream/article/details/17717873

*/
//    String s lenght does not matter . due to have to run out the p++++6++++++++++++++++`--+``

public class Solution {
    public boolean isMatch(String s, String p) {
        return isM(s,p,0,0);
    }
    
    public static boolean isM(String s, String p, int i, int j){  
        if(j >= p.length()){         
            return i >= s.length();   
        }  
        if(j == p.length()-1){  
            return (i == s.length()-1) && (s.charAt(i)==p.charAt(j) || p.charAt(j)==‘.‘);  
        }  
 
 // bb
 // bc  .c
        if(j+1<p.length() && p.charAt(j+1) != ‘*‘){  
            if(i == s.length()){    
                return false;  
            }  
            if(s.charAt(i)==p.charAt(j) || p.charAt(j)==‘.‘){   
                return isM(s, p, i+1, j+1);     
            }else{    
                return false;  
            }  
        }  
          
 // bbcd                   ab
 // b*cd or .*cd           .*  true due to  .....        
        while(i<s.length() && j<p.length() && (s.charAt(i)==p.charAt(j) || p.charAt(j)==‘.‘)){  

            if(isM(s, p, i, j+2)){  
                return true;  
            }  
            i++;  
        }  
          
// bbcd
// c*bbcd
        return isM(s, p, i, j+2);  
    }  
}

 

Regular Expression Matching

原文:http://www.cnblogs.com/leetcode/p/4005605.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!