码迷,mamicode.com
首页 > 其他好文 > 详细

Wildcard Matching

时间:2016-07-17 14:21:25      阅读:200      评论:0      收藏:0      [点我收藏+]

标签:

Implement wildcard pattern 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).

Example
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

分析:
这题也是DP问题,横轴是S, 纵轴是P(含有?和*),那么我们可以得到:

if (p.charAt(i - 1) == s.charAt(j - 1) || p.charAt(i - 1) == ‘?‘) {
  match[i][j] = match[i - 1][j - 1];
} else if (p.charAt(i - 1) == ‘*‘) {
  match[i][j] = match[i - 1][j - 1] || match[i - 1][j] || match[i][j - 1];

  // match[i][j - 1] 指的是用* 替换S中1个j或多个j之前的character,当然那些character可以是连续的。
}

 1 public class Solution {
 2     /**
 3      * @param s: A string 
 4      * @param p: A string includes "?" and "*"
 5      * @return: A boolean
 6      */
 7     public boolean isMatch(String s, String p) {
 8         if (s == null || p == null)
 9             return false;
10         boolean[][] match = new boolean[p.length() + 1][s.length() + 1];
11         match[0][0] = true;
12         for (int i = 1; i < match[0].length; i++) {
13             match[0][i] = false;
14         }
15         
16         for (int i = 1; i < match.length; i++) {
17             if (p.charAt(i - 1) == *) {
18                 match[i][0] = match[i - 1][0];
19             } 
20         }
21         
22         for (int i = 1; i < match.length; i++) {
23             for (int j = 1; j < match[0].length; j++) {
24                 if (p.charAt(i - 1) == s.charAt(j - 1) || p.charAt(i - 1) == ?) {
25                     match[i][j] = match[i - 1][j - 1];
26                 } else if (p.charAt(i - 1) == *) {
27                     match[i][j] = match[i - 1][j - 1] || match[i - 1][j] || match[i][j - 1];
28                 }
29             }
30         }
31         
32         return match[p.length()][s.length()];
33     }
34 }

 

Wildcard Matching

标签:

原文地址:http://www.cnblogs.com/beiyeqingteng/p/5677739.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!