標籤:
問題描述:
Implement regular expression matching with support for ‘.‘ and ‘*‘.
‘.‘ Matches any single character.‘*‘ Matches zero or more of the preceding element.http://i.cnblogs.com/EditPosts.aspx?opt=1The matching should cover the entire input string (not partial).The function prototype should be:bool isMatch(const char *s, const char *p)Some examples:isMatch("aa","a") → falseisMatch("aa","aa") → trueisMatch("aaa","aa") → falseisMatch("aa", "a*") → trueisMatch("aa", ".*") → trueisMatch("ab", ".*") → trueisMatch("aab", "c*a*b") → true
解題思路:
從字串s和p的位置sp,pp處分別開始匹配,運用遞迴的方法不斷縮小字串的比較長度,最後回溯回來比較結果。
假設現在走到分別走到sp,pp處。則分為下面幾種情況:
(1)如果pp的位置已經越界,那麼若sp也已越界,那麼則返回true;否則說明s字串還有長度,不匹配,返回false;
(2)pp的位置為p的最後一位,那麼此時只能一一匹配,若不匹配則返回false;否則進行下一位比較;
(3)pp的位置比較靠前,那麼比較pp的下一位。如果下一位不是‘*‘,則只能一一匹配,若不匹配則返回false;否則進行下一位比較。如果下一位是‘*‘,則將pp的位置向後移動兩位,sp的位置從現在開始進行暴力比較,每次向後移一位進行遞迴比較。
代碼如下:
1 public class Solution { 2 public static boolean isMatch(String s, String p) { 3 if (s == null) 4 return p == null; 5 if (p == null) 6 return s == null; 7 return helper(s, p, 0, 0); 8 } 9 private static boolean helper(String s, String p, int sp, int pp) {10 if (pp >= p.length())11 return sp >= s.length();12 // pp comes to end13 if (pp == p.length() - 1) {14 if (sp >= s.length()15 || (s.charAt(sp) != p.charAt(pp) && p.charAt(pp) != ‘.‘))16 return false;17 else18 return helper(s, p, sp + 1, pp + 1);19 }20 // p.charAt(pp+1)!=‘*‘21 if (p.charAt(pp + 1) != ‘*‘) {22 if (sp >= s.length()23 || (s.charAt(sp) != p.charAt(pp) && p.charAt(pp) != ‘.‘))24 return false;25 else26 return helper(s, p, sp + 1, pp + 1);27 }28 // p.charAt(pp+1)==‘*‘29 while (sp < s.length()30 && (p.charAt(pp) == ‘.‘ || s.charAt(sp) == p.charAt(pp))) {31 if (helper(s, p, sp, pp + 2))32 return true;33 sp++;34 }35 return helper(s, p, sp, pp + 2);36 }37 }
Java [leetcode 10] Regular Expression Matching