/*
思路:只有當模式串和字符串同時等於\0,才可以認為兩個串匹配。
在匹配中,對於每個位的匹配可以分為三種情況
1、(相應位匹配||模式串為.&&字符串不是\0)&&模式串下一位是*
2、(相應位匹配||模式串為.&&字符串不是\0)&&模式串下一位不是*
3、相應位不匹配&&(模式位不為.||字符串是\0)
對應1,最復雜。分為*取0,*取1,*>=2三種情況。
*取0對應跳過當前匹配位,繼續尋找patter的下一個匹配位,str不變,pattern+2
*取1對應當前匹配位算一次成功匹配,str+1,pattern+2
*取>=2對應一次成功匹配,繼續匹配字符串的下一位是否匹配,str+1,pattern不變
三者取或。即只要有一種情況能匹配成功認為字符串就是匹配成功的。
對應2,相當於一次成功匹配,str+1,pattern+1
對應3,匹配失敗,直接返回false
*/
class Solution {
public:
bool match(char* str, char* pattern)
{
if(str==NULL||pattern==NULL)
return false;
return matchCore(str,pattern);
}
bool matchCore(char* str, char* pattern)
{
if(*str=='\0'&&*pattern=='\0')
return true;
if(*str!='\0'&&*pattern=='\0')
return false;
if(*(pattern+1)=='*')
{
if(*pattern==*str||(*pattern=='.'&&*str!='\0'))
/*
matchCore(str,pattern+2):模式串未匹配
matchCore(str+1,pattern):模式串已經匹配成功,嘗試匹配下一個字符串
matchCore(str+1,pat+2):模式串已經成功匹配,並且不匹配下一個字符串內容 注意這里 matchCore(str+1,pat+2)重復考慮了(代碼中已經去除),謝謝@chlq的指出 */
return matchCore(str+1,pattern)||matchCore(str,pattern+2);
else
return matchCore(str,pattern+2);
}
if(*str==*pattern||(*pattern=='.'&&*str!='\0'))
return matchCore(str+1,pattern+1);
return false;
}
};