10. Regular Expression Matching

来源:互联网 发布:mysql 事务 存储过程 编辑:程序博客网 时间:2024/04/24 16:51

只能说这样的题太烧脑了,只好在Discussion中找答案


考虑递归的方法,分别考虑第二位上有没有 * ,如果没有,就先比较第一位,接着递归比较后面的子字符串;

如果有 * 的话,那么*可能匹配多个字符串,用while循环,匹配一个时判断两个字符串后面的子串是不是match,是就return true,否则匹配两个在看,不行再三个,知道两个字符串的子串的第一个字符不匹配。


要注意一点的是C++与Java操作子串的区别



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

package l10;public class Solution {public boolean matchFirst(String s, String p) {if("".equals(s) || "".equals(p))return "".equals(s) && "".equals(p);String st = s.substring(0, 1), pt = p.substring(0, 1);return st.equals(pt) || (".".equals(pt) && !"".equals(st));}    public boolean isMatch(String s, String p) {    if("".equals(p))return "".equals(s);    if(p.length() == 1)return s.length() == 1 && matchFirst(s, p);    if(!"*".equals(p.substring(1, 2))) {    if(! matchFirst(s, p))return false;    return isMatch(s.substring(1), p.substring(1));    } else {    if(isMatch(s, p.substring(2)))return true;    while(matchFirst(s, p)) {    s = s.substring(1);    if(isMatch(s, p.substring(2)))return true;    }    }            return false;    }}


0 0