LeetCode 010-Regular Expression Matching

来源:互联网 发布:linux 添加输入法 编辑:程序博客网 时间:2024/05/22 09:04

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
难度:难

代码:该题要理清思路 从p的length入手,分情况讨论

public class Solution {    public boolean isMatch(String s, String p) {<span style="white-space:pre"></span>if (p.length() == 0)<span style="white-space:pre"></span>return s.length() == 0;<span style="white-space:pre"></span>if (s.length() == 0) {<span style="white-space:pre"></span>if (p.length() == 1)<span style="white-space:pre"></span>return false;<span style="white-space:pre"></span>if (p.charAt(1) == '*')<span style="white-space:pre"></span>return isMatch(s, p.substring(2));<span style="white-space:pre"></span>return false;<span style="white-space:pre"></span>}<span style="white-space:pre"></span>if (p.length() == 1) {<span style="white-space:pre"></span>if (p.charAt(0) == '.' && s.length() == 1)<span style="white-space:pre"></span>return true;<span style="white-space:pre"></span>return s.equals(p);<span style="white-space:pre"></span>}<span style="white-space:pre"></span>if (p.length() >= 2 && p.charAt(1) != '*') {<span style="white-space:pre"></span>// if p(1) is not *, we need p(0) equals to s(0) or p(0) equals '.'<span style="white-space:pre"></span>if (p.charAt(0) == s.charAt(0) || p.charAt(0) == '.'<span style="white-space:pre"></span>&& s.length() != 0)<span style="white-space:pre"></span>// check if the left is also match<span style="white-space:pre"></span>return isMatch(s.substring(1), p.substring(1));<span style="white-space:pre"></span>return false;<span style="white-space:pre"></span>} else {<span style="white-space:pre"></span>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));}<span style="white-space:pre"></span>}}

0 0