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
借鑑了網上博主c語言的思路,從後往前匹配,不用考慮越界情況。(回溯法)
public static boolean isMatch(String s, String p) {
return myMacth(s,s.length()-1,p,p.length()-1);
}
private static boolean myMacth(String s,int i,String p,int j){
System.out.println(i+" "+j);
if(j==-1)
if(i==-1)
return true;
else return false;
if(p.charAt(j)=='*'){//若碰到*,則先是判斷*前字符與s中是否相等,相等則下一步,不相等則跳過這兩位,進入下一步。
if(i >= 0 &&(p.charAt(j-1)=='.'||p.charAt(j-1)==s.charAt(i))){
if(myMacth(s,i-1,p,j))
return true;
}
return myMacth(s,i,p,j-2);
}
if(i==-1&&j>=0) return false;//此處判斷很關鍵,s先遍歷完的情況下,此時p沒有遍歷完。
if(p.charAt(j)=='.'||p.charAt(j)==s.charAt(i))
return myMacth(s,i-1,p,j-1);
return false;
}