码迷,mamicode.com
首页 > 编程语言 > 详细

Java for LeetCode 010 Regular Expression Matching

时间:2015-04-28 22:30:32      阅读:234      评论:0      收藏:0      [点我收藏+]

标签:

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

这道题初学者或多或少都参考了网上的答案,主要难点有以下
一、要理解正则表达式中.和*的含义,“.”代表任意字符,但是“a*”代表“”,“a”,“aa”,“aaa”……这一点比较容易让人犯迷糊
二、必须完全比配,即isMatch("aa","aaa") → false
三、第一个参数String s 是不含有“.”和“*”,因此不要把程序复杂化
Java实现如下:
static public boolean isMatch(String s, String p) {
        // 如果从s长度入手,s.length() == 0时("","a*")、("","a*b*")都会返回true
            if(p.length() == 0)
                return s.length() == 0;  
            if(p.length() == 1)
                return s.length() == 1 && (p.charAt(0) == ‘.‘ || s.charAt(0) == p.charAt(0));
            if(p.charAt(1) != ‘*‘){
                if(s.length() == 0 || (p.charAt(0) != ‘.‘ && s.charAt(0) != p.charAt(0)))
                    return false;
                return isMatch(s.substring(1), p.substring(1));    
     
            }else {
                if(isMatch(s, p.substring(2)))
                    return true;
                else{
                    int len = s.length();//空间换时间
                    int i = 0; 
                    while(i<len && (p.charAt(0) == ‘.‘ || p.charAt(0) == s.charAt(i))){
                        if(isMatch(s.substring(i+1), p.substring(2)))
                            return true;
                        i++;
                    }        
                }  
                    return false;
                } 
        }

 



Java for LeetCode 010 Regular Expression Matching

标签:

原文地址:http://www.cnblogs.com/tonyluis/p/4464059.html

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