Given an input string (
s
) and a pattern (p
), 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).
Note:
s
could be empty and contains only lowercase lettersa-z
.p
could be empty and contains only lowercase lettersa-z
, and characters like.
or*
.Example 1:
Input: s = "aa" p = "a" Output: false Explanation: "a" does not match the entire string "aa".Example 2:
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: 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:
Input: s = "mississippi" p = "mis*is*p*." Output: false
题目中s为源字符串,p为带有通配符.和*的匹配字符串,*表示前一个字符的重复次数,且可以为0,因为a*和.*是比较难处理的两种情况,这里还是考虑采用动态规划的思想来处理。分为以下几种情况:
1. s为####a, p为#####.*, 这里.*要么匹配a,要么就直接为空两种情况,因此下一步比较s[0:i-1]与p, s与p[0:j-2],这两个中有一个匹配则s和p都是匹配的
2. s为#####a, p为#####a*, 这里a*要么匹配a, 要么就直接为空两种情况, 因此下一步比较s[0:i-1]与p, s与p[0:j-2]
3. s为#####a, p为#####b*, 这里别无选择,b*只能为空
4. s为#####a, p为#####., 这里下一步比较s[0:i-1]与p[0:j-1]即可
5. s为#####a, p为#####a, 同4
6. 其它情况均为不匹配
由此可得到动态规划的递推式, 上面已经描述的比较清楚了, 这里不再给出递推式, 然后注意迭代顺序就好了,本题与Wildcard Matching的思想比较类似, 直接给出golang实现代码:
func isMatch(s string, p string) bool {
matchArray := make([][]bool, len(s)+1)
for i := 0; i < len(s)+1; i++ {
matchArray[i] = make([]bool, len(p)+1)
for j := 0; j < len(p)+1; j++ {
matchArray[i][j] = false
}
}
for j := 0; j < len(p)+1; j++ {
for i := 0; i < len(s)+1; i++ {
if i == 0 && j == 0 {
matchArray[i][j] = true
continue
}
if j == 0 {
matchArray[i][j] = false
continue
}
if i == 0 {
if j == 2 && p[j-1] == '*' {
matchArray[i][j] = true
} else if p[j-1] == '*' {
matchArray[i][j] = matchArray[i][j-2]
} else {
matchArray[i][j] = false
}
continue
}
if p[j-1] == '*' && p[j-2] == '.' {
matchArray[i][j] = matchArray[i][j-2] || matchArray[i-1][j]
} else if p[j-1] == '*' && p[j-2] != '.' && s[i-1] == p[j-2] {
matchArray[i][j] = matchArray[i-1][j] || matchArray[i][j-2]
} else if p[j-1] == '*' && p[j-2] != '.' && s[i-1] != p[j-2] {
matchArray[i][j] = matchArray[i][j-2]
} else if p[j-1] == '.' {
matchArray[i][j] = matchArray[i-1][j-1]
} else if p[j-1] == s[i-1] {
matchArray[i][j] = matchArray[i-1][j-1]
} else {
matchArray[i][j] = false
}
}
}
return matchArray[len(s)][len(p)]
}