Wildcard Matching leetcode java

來源:互聯網
上載者:User

標籤:code   ring   不成功   問題   const   over   wildcard   ==   main   

描述
Implement wildcard paern matching with support for ‘?‘ and ‘*‘.
‘?‘ Matches any single character. ‘*‘ Matches any sequence of characters (including the empty
sequence).
The 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") → false
isMatch("aa","aa") → true
isMatch("aaa","aa") → false
isMatch("aa", "*") → true
isMatch("aa", "a*") → true
isMatch("ab", "?*") → true
isMatch("aab", "c*a*b") → false

分析
跟上一題很類似。
主要是‘*‘ 的匹配問題。p 每遇到一個‘*‘,就保留住當前‘*‘ 的座標和 s 的座標,然後 s 從前
往後掃描,如果不成功,則 s++,重新掃描

代碼

 1 public class WildcardMatch { 2  3     public static void main(String[] args) { 4         // TODO Auto-generated method stu  5         String s= "aab"; 6         String p="*"; 7         System.out.println(isMatch(s,p)); 8     } 9 //    遞迴10         public static boolean isMatch(String s, String p) {11         if (p.length() == 0)12                 return s.length() == 0;13             14         if (p.charAt(0) == ‘*‘) {    15                 16         while (p!=null&&p.startsWith("*")) {17             18             p=p.substring(1); //跳過*19         }    20         if (p==null) 21             return true;22         while (s!= null && !isMatch(s, p)) 23             s=s.substring(1);24         return s != null;25       }26       27         else if (p.charAt(0) == ‘\0‘ || s.charAt(0) == ‘\0‘) return p.charAt(0) == s.charAt(0);28         else if (p.charAt(0) == s.charAt(0) || p.charAt(0) == ‘?‘) {29             30             return isMatch(s.substring(1), p.substring(1));31         }32         else return false;33         }



34 //迭代版 35 public static boolean isMatch2(String s, String p) { 36 int i = 0; 37 int j = 0; 38 int star = -1; 39 int mark = -1; 40 while (i < s.length()) { 41 if (j < p.length() 42 && (p.charAt(j) == ‘?‘ || p.charAt(j) == s.charAt(i))) { 43 ++i; 44 ++j; 45 } else if (j < p.length() && p.charAt(j) == ‘*‘) { 46 star = j++; 47 mark = i; 48 } else if (star != -1) { 49 j = star + 1; 50 i = ++mark; 51 } else { 52 return false; 53 } 54 } 55 while (j < p.length() && p.charAt(j) == ‘*‘) { 56 ++j; 57 } 58 return j == p.length(); 59 }60 }

 

Wildcard Matching leetcode java

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在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.