leetcode Regular Expression Matching

来源:互联网 发布:切尔西靴品牌推荐知乎 编辑:程序博客网 时间:2024/06/05 06:32

Regular Expression Matching原题地址:

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") → falseisMatch("aa","aa") → trueisMatch("aaa","aa") → falseisMatch("aa", "a*") → trueisMatch("aa", ".*") → trueisMatch("ab", ".*") → trueisMatch("aab", "c*a*b") → true
还是要注意类似“a*a”和"aaa"这种情况,所以遇到*后先不做展开向后匹配,再慢慢展开进行匹配。

public class Solution {    public boolean isMatch(String s, String p) {        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)return false;elsereturn (s.charAt(0) == p.charAt(0) || p.charAt(0) == '.') && isMatch(s.substring(1), p.substring(1));} else {while (s.length() > 0 && (p.charAt(0) == s.charAt(0) || p.charAt(0) == '.')) {if (isMatch(s, p.substring(2)))return true;s = s.substring(1);}return isMatch(s, p.substring(2));}    }}


0 0