這是遇到的第一個(gè)困難題,自己先寫了一遍,結(jié)果被邊界條件繞暈了,不過和遞歸方法的思想還是一致的。關(guān)鍵點(diǎn)就在于*,*可以匹配0次或多次,放在遞歸條件里,每一步判斷,其實(shí)就是匹配或者不匹配。
遞歸方法解法如下:
class?Solution?{
????public?boolean?isMatch(String?s,?String?p)?{
????????if?(p.isEmpty())?{
????????????return?s.isEmpty();
????????}
????????boolean?firstMatch?=?!s.isEmpty()?&&?(s.charAt(0)?==?p.charAt(0)
????????????||?p.charAt(0)?==?'.');
????????if?(p.length()?>=?2?&&?p.charAt(1)?==?'*')?{
????????????return?(firstMatch?&&?isMatch(s.substring(1),?p))?
????????????????||?isMatch(s,?p.substring(2));?
????????}?else?{
????????????return?firstMatch?&&?isMatch(s.substring(1),?p.substring(1));
????????}
????}
}
下面還會看下動(dòng)態(tài)規(guī)劃的解法,動(dòng)態(tài)規(guī)劃在于找到臨界點(diǎn)和迭代表達(dá)式,這里的dp[i][j]代表第i位和第j位以后的字符串是夠匹配,i代表s的下標(biāo),j代表p的下標(biāo)。
public?boolean?isMatch(String?s,?String?p)?{
????????int?m?=?s.length();
????????int?n?=?p.length();
????????//?s位置為i,p位置為j是否能匹配,比著下標(biāo)大1
????????boolean[][]?dp?=?new?boolean[m?+?1][n?+?1];
????????//?s和p都為空的情況,能匹配
????????dp[0][0]?=?true;
????????//?i從0開始,代表s為空時(shí)也也能進(jìn)行匹配
????????for?(int?i?=?0;?i?<=?m;?i++)?{
????????????//?j從1開始,說明p為空時(shí)不能匹配上,默認(rèn)為false即可
????????????for?(int?j?=?1;?j?<=?n;?j++)?{
????????????????if?(p.charAt(j?-?1)?==?'*')?{
????????????????????//?s當(dāng)前位置,和p前一個(gè)位置如果相同
????????????????????if?(isMatch(s,?p,?i,?j?-?1))?{
????????????????????????//?s當(dāng)前位置,和p前一個(gè)位置如果相同,有兩種選擇
????????????????????????//?1.不匹配a*組合,那么取決于dp[i][j?-?2]
????????????????????????//?2.用*匹配,要看i - 2到j(luò) - 1位置是否能匹配
????????????????????????dp[i][j]?=?dp[i][j?-?2]?||?dp[i?-?1][j];?
????????????????????}?else?{
????????????????????????//?不同的話,代表這個(gè)*只能取0,那么依賴于dp[i][j?-?2]是否可匹配
????????????????????????dp[i][j]?=?dp[i][j?-?2];
????????????????????}??
????????????????}?else?{
????????????????????//?當(dāng)前位置相同,且之前也匹配
????????????????????dp[i][j]?=?isMatch(s,?p,?i,?j)?&&?dp[i?-?1][j?-?1];
????????????????}????
????????????}????????
????????}
????????return?dp[m][n];?
????}
????/**
?????*?判斷s,p對應(yīng)位置上是否匹配,i,j代表位置,而非下標(biāo)
?????*/
????public?boolean?isMatch(String?s,?String?p,?int?i,?int?j)?{
????????if?(i?==?0)?{
????????????return?false;
????????}
????????if?(s.charAt(i?-?1)?==?p.charAt(j?-?1))?{
????????????return?true;
????????}
????????return?p.charAt(j?-?1)?==?'.';
????}