10. Regular Expression Matching(js)

10. Regular Expression Matchingexpress

Given an input string (s) and a pattern (p), implement regular expression matching with support for '.' and '*'.spa

'.' Matches any single character.
'*' Matches zero or more of the preceding element.

The matching should cover the entire input string (not partial).code

Note:blog

  • s could be empty and contains only lowercase letters a-z.
  • p could be empty and contains only lowercase letters a-z, and characters like . or *.

Example 1:ip

Input:
s = "aa"
p = "a"
Output: false
Explanation: "a" does not match the entire string "aa".

Example 2:element

Input:
s = "aa"
p = "a*"
Output: true
Explanation: '*' means zero or more of the precedeng element, 'a'. Therefore, by repeating 'a' once, it becomes "aa".

Example 3:字符串

Input:
s = "ab"
p = ".*"
Output: true
Explanation: ".*" means "zero or more (*) of any character (.)".

Example 4:input

Input:
s = "aab"
p = "c*a*b"
Output: true
Explanation: c can be repeated 0 times, a can be repeated 1 time. Therefore it matches "aab".

Example 5:string

Input:
s = "mississippi"
p = "mis*is*p*."
Output: false
題意:給定一個字符串和匹配模板,返回是否匹配成功
代碼以下(js):
var isMatch = function(s, p) {
    //1.若是s爲空,p也爲空,返回true
      if(p.length===0) return s.length===0;  
      //2.若是s長度爲1,p長度也爲1,若p=s或者p='.'則返回true
      if(p.length===1)  return (s.length==1) && (s[0]===p[0] || p[0]==='.');
            //3.若p的第二個字符不爲*
      if(p[1]!=='*'){
          //若是s爲空,返回false
          if(s.length===0) return false;
          return (s[0]===p[0] || p[0]==='.') && isMatch(s.substr(1),p.substr(1));
      }
      //4.若p的第二個字符爲*,比較s的第一個字符和p的第一個字符
      while(s.length>0 && (s[0]===p[0] || p[0]==='.') ){
          if(isMatch(s,p.substr(2))) return true;
          s=s.substr(1);
      }
    return isMatch(s,p.substr(2))
};
相關文章
相關標籤/搜索