Java [leetcode 10] Regular Expression Matching

來源:互聯網
上載者:User

標籤:

問題描述:

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

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.