Wildcard Matching

描述

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).

The function prototype should be:

  1. bool isMatch(const char *s, const char *p)

Some examples:

  1. isMatch("aa","a") false
  2. isMatch("aa","aa") true
  3. isMatch("aaa","aa") false
  4. isMatch("aa", "*") true
  5. isMatch("aa", "a*") true
  6. isMatch("ab", "?*") true
  7. isMatch("aab", "c*a*b") false

分析

跟上一题很类似。

主要是''的匹配问题。p每遇到一个'',就保留住当前'*'的坐标和s的坐标,然后s从前往后扫描,如果不成功,则s++,重新扫描。

递归版

  1. // Wildcard Matching
  2. // 递归版,会超时,用于帮助理解题意
  3. // 时间复杂度O(n!*m!),空间复杂度O(n)
  4. class Solution {
  5. public boolean isMatch(String s, String p) {
  6. return isMatch(s, 0, p, 0);
  7. }
  8. private boolean isMatch(String s, int i, String p, int j) {
  9. if (i == s.length() && j == p.length()) return true;
  10. if (i == s.length() || j == p.length()) return false;
  11. if (p.charAt(j) == '*') {
  12. while (j < p.length() && p.charAt(j) == '*') ++j; //skip continuous '*'
  13. if (j == p.length()) return true;
  14. while (i < s.length() && !isMatch(s, i, p, j)) ++i;
  15. return i < s.length();
  16. }
  17. else if (p.charAt(j) == s.charAt(i) || p.charAt(j) == '?')
  18. return isMatch(s, ++i, p, ++j);
  19. else return false;
  20. }
  21. }

迭代版

  1. // Wildcard Matching
  2. // 迭代版,时间复杂度O(n*m),空间复杂度O(1)
  3. public class Solution {
  4. public boolean isMatch(String s, String p) {
  5. int i = 0, j = 0;
  6. int ii = -1, jj = -1;
  7. while (i < s.length()) {
  8. if (j < p.length() && p.charAt(j) == '*') {
  9. // skip continuous '*'
  10. while (j < p.length() && p.charAt(j) == '*') ++j;
  11. if (j == p.length()) return true;
  12. ii = i;
  13. jj = j;
  14. }
  15. if (j < p.length() && (p.charAt(j) == '?' || p.charAt(j) == s.charAt(i))) {
  16. ++i; ++j;
  17. } else {
  18. if (ii == -1) return false;
  19. ++ii;
  20. i = ii;
  21. j = jj;
  22. }
  23. }
  24. // skip continuous '*'
  25. while (j < p.length() && p.charAt(j) == '*') ++j;
  26. return i == s.length() && j == p.length();
  27. }
  28. }

相关题目

原文: https://soulmachine.gitbooks.io/algorithm-essentials/content/java/string/wildcard-matching.html