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

Regular Expression Matching

时间:2014-10-08 18:03:55      阅读:184      评论:0      收藏:0      [点我收藏+]

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

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 match(char s,char p)
    {
        return s==p||p=='.';
    }
    public boolean isMatch(String s, String p)
    {
        int sLen = s.length();
        int pLen = p.length();
        int i;
        int j;
        int k;
        boolean[][] match = new boolean[sLen+1][pLen+1];
        match[0][0]=true;
        for(i=0;i<sLen;i++)
        {
            match[i+1][0]=false;
        }
        for(j=0;j<pLen;j++)
        {
            if(p.charAt(j)=='*')
            {
                match[0][j+1]=match[0][j-1];
            }
            else
            {
                match[0][j+1]=false;
            }
        }
        for (i = 0; i < sLen; i++ )
        {
            for (j = 0; j < pLen; j++ )
            {
                if (p.charAt(j) == '*')
                {
                    //0个、1个或多个
                    match[i+1][j+1]=match[i+1][j-1]||match[i+1][j]||(match(s.charAt(i),p.charAt(j-1))&&match[i][j+1]);
                }
                else
                {
                    match[i+1][j+1]=match(s.charAt(i),p.charAt(j))&&match[i][j];
                }
            }
        }
        return match[sLen ][pLen ];
    }
}


Regular Expression Matching

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

原文地址:http://blog.csdn.net/jiewuyou/article/details/39894917

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