标签: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
标签:code ring 不成功 问题 const over wildcard == main
原文地址:https://www.cnblogs.com/ncznx/p/9189489.html