Implement regular expression matching with support for ‘.’ and ‘*’.git
‘.’ Matches any single character.
‘*’ Matches zero or more of the preceding element.github
The matching should cover the entire input string (not partial).express
The function prototype should be:
bool isMatch(const char *s, const char *p)bash
Some examples:markdown
isMatch("aa","a") → false
isMatch("aa","aa") → true
isMatch("aaa","aa") → false
isMatch("aa", "a*") → true
isMatch("aa", ".*") → true
isMatch("ab", ".*") → true
isMatch("aab", "c*a*b") → true
字符串的模式匹配問題!測試
核心的思路是一個動態規劃spa
dp[i][j]表示字串 s[i…len(s)], p[j…len(p)] 是否能夠匹配。.net
那麼狀態轉移方程以下:prototype
dp[i][j] = c. p[j+1] != *. code
if s[i] == p[j]
dp[i][j] = dp[i+1][j+1]
else
dp[i][j] = false
c p[j+1] == ‘’ (這個狀況下,要擴展 , dp[i][j] 從拓展的狀況下,選擇一個是真的結果)
if( s[i] == p[j] || p[j] == '.' && (*s) != '\0')
當s[i] 和 p[j] 同樣的時候,例如 aba, a*b這個時候,i = 0, j = 0, 天然能夠匹配a a
若是p[j] == . 由於他能夠匹配任何字符,因此和相等關係有基本同樣的方式。
而且每一步匹配都要遞增 i 的值,若是有成立的,則返回true,不然到匹配終了,返回通配符匹配完成後的結果。
class Solution {
public:
bool isMatch(string s, string p) {
//若是字符串爲空,那麼模式串爲空則返回true,不然返回false
if (p.empty())
return s.empty();
//求模式串的長度
int s_len = s.length();
//求字符串的長度
int p_len = p.length();
if (p[1] == '*')
{
while ((s[0] != '\0' && p[0] == '.') || (s[0] == p[0]))
{
//字符串與模式串匹配0/1/2...個字符的狀況
if (isMatch(s, p.substr(2, p_len - 2)))
return true;
s = s.substr(1, s_len - 1);
}
// 字符串與模式串不能匹配
return isMatch(s, p.substr(2, p_len - 2));
}
else
{
if ((s[0] != '\0' && p[0] == '.') || (s[0] == p[0]))
return isMatch(s.substr(1, s_len - 1), p.substr(1, p_len - 1));
return false;
}
}
};