Regular Expression Matching

来源:互联网 发布:好的手机壁纸软件 编辑:程序博客网 时间:2024/06/07 15:59
题目:

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") return false
isMatch("aa","aa") return true
isMatch("aaa","aa") return false
isMatch("aa", "a*") return true
isMatch("aa", ".*") return true
isMatch("ab", ".*") return true
isMatch("aab", "c*a*b") return true

注意:这里的a*表示a可以重复0次或者多次,不是a和*分开的。

这个问题可以简化为两种情况:第二个字符是'*'和第二个字符不是'*'。

public static boolean isMatch(String s, String p) {if(p.length() == 0)            return s.length() == 0;         //p's length 1 is special case            if(p.length() == 1 || p.charAt(1) != '*'){        // if the length of s is 0 or the first does not match, return false            if(s.length() < 1 || (p.charAt(0) != '.' && s.charAt(0) != p.charAt(0)))                return false;            // otherwise, compare the rest of the string of s and p.            return isMatch(s.substring(1), p.substring(1));             }else{            int len = s.length();            //case 2.1: a char & '*' can stand for 0 element,此时 i < 0            //case 2.2: a char & '*' can stand for 1 or more preceding element, so try every sub string            int i = -1;             while(i<len && (i < 0 || p.charAt(0) == '.' || p.charAt(0) == s.charAt(i))){                if(isMatch(s.substring(i+1), p.substring(2)))                    return true;                i++;            }            return false;        }    }


0 0