码迷,mamicode.com
首页 > 其他好文 > 详细

Regular Expression Matching

时间:2014-10-04 06:16:56      阅读:232      评论:0      收藏:0      [点我收藏+]

标签:style   blog   http   color   io   ar   for   strong   sp   

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

标签:style   blog   http   color   io   ar   for   strong   sp   

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

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!