To prove safety OFFER ---- 19, regular expression matching (js achieve)

topic

Implement comprises a function to match '' and ' ' in a regular expression. Mode character '.' Represents any one character ' ' is represented in front of the character may be any number of times (including 0 time). In this problem, the match is a whole pattern matches all characters of the string. For example, the string "aaa" mode and "aa" and "ab & AC A" match, but the "aa.a" and "ab * a" does not match


I thought
when the mode of the second character is not "*" is:

  1. If the first character and the first character in the pattern matches the character string and a character backward modes, then the remaining matches.
  2. If the first character and the first character pattern does not match the phase directly returns false.

And when the mode of the second character is "*" is:
If the first character string pattern does not match with the first character, then after the mode shift two characters continue to match. If the first character string with the first character pattern matching, there are three possible ways to match:

  1. Mode 2 after shifting character, corresponding to x * is ignored;
  2. After shifting a string of characters, the characters after the mode shift 2;
  3. After the move 1 character string, the same pattern that continues to match the next character place, because * matches a number;
function match(s, pattern) {
  // write code here
  if (s == null || pattern == null) {
    return false
  }
  return checkMatch(s, pattern, 0, 0)
}

function checkMatch(s, pattern, i, j) {
  if (i === s.length && j === pattern.length) {
    return true
  }
  if (j === pattern.length && i !== s.length) {
    return false
  }
  // 第二个符号为 *
  if (pattern[j + 1] && pattern[j + 1] === '*') {
    // 第一个字符匹配
    if (s[i] === pattern[j] || (pattern[j] === '.' && i !== s.length)) {
      return checkMatch(s, pattern, i, j + 2) || checkMatch(s, pattern, i + 1, j) || checkMatch(s, pattern, i + 1, j + 2)
    // 第一个字符不匹配
    } else {
      return checkMatch(s, pattern, i, j + 2)
    }
  }
  if (pattern[j] === s[i] || (pattern[j] === '.' && i !== s.length)) {
    return checkMatch(s, pattern, i + 1, j + 1)
  }
  return false
}

Guess you like

Origin blog.csdn.net/qq_40816360/article/details/95177517