10Regular Expression Matching

来源:互联网 发布:火炬红包群 淘宝群 编辑:程序博客网 时间:2024/05/22 04:35
 <p style="box-sizing: border-box; margin-top: 0px; margin-bottom: 10px; color: rgb(51, 51, 51); font-family: 'Helvetica Neue', Helvetica, Arial, sans-serif; font-size: 14px; line-height: 30px;">Implement regular expression matching with support for <code style="box-sizing: border-box; font-family: Menlo, Monaco, Consolas, 'Courier New', monospace; font-size: 12.6000003814697px; padding: 2px 4px; color: rgb(199, 37, 78); border-radius: 4px; background-color: rgb(249, 242, 244);">'.'</code> and <code style="box-sizing: border-box; font-family: Menlo, Monaco, Consolas, 'Courier New', monospace; font-size: 12.6000003814697px; padding: 2px 4px; color: rgb(199, 37, 78); border-radius: 4px; background-color: rgb(249, 242, 244);">'*'</code>.</p><pre style="box-sizing: border-box; overflow: auto; font-family: Menlo, Monaco, Consolas, 'Courier New', monospace; font-size: 13px; padding: 9.5px; margin-top: 0px; margin-bottom: 10px; line-height: 1.42857143; color: rgb(51, 51, 51); word-break: break-all; word-wrap: break-word; border: 1px solid rgb(204, 204, 204); border-radius: 4px; background-color: rgb(245, 245, 245);">'.' Matches any single character.'*' Matches zero or more of the preceding element.The matching should cover the <span style="box-sizing: border-box; font-weight: 700;">entire</span> 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
 public boolean isMatch(String s, String p) {                if (p.length() == 0) {return s.length() == 0;} // special caseif (p.length() == 1) { // if the length of s is 0, return falseif (s.length() < 1) {return false;} //if the first does not match, return falseelse if ((p.charAt(0) != s.charAt(0)) && (p.charAt(0) != '.')) {return false;} // otherwise, compare the rest of the string of s and p.else {return isMatch(s.substring(1), p.substring(1));}} // case 1: when the second char of p is not '*'if (p.charAt(1) != '*') {if (s.length() < 1) {return false;}if ((p.charAt(0) != s.charAt(0)) && (p.charAt(0) != '.')) {return false;} else {return isMatch(s.substring(1), p.substring(1));}} // case 2: when the second char of p is '*', complex case.else {//case 2.1: a char & '*' can stand for 0 elementif (isMatch(s, p.substring(2))) {return true;} //case 2.2: a char & '*' can stand for 1 or more preceding element, //so try every sub stringint i = 0;while (i<s.length() && (s.charAt(i)==p.charAt(0) || p.charAt(0)=='.')){if (isMatch(s.substring(i + 1), p.substring(2))) {return true;}i++;}return false;}            }

0 0
原创粉丝点击