问题描述
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: 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
问题分析
这道题目和之前的leetcode010:Regular Expression Matching 规则稍有不同,就是对于‘*‘ 号这次代表的是匹配任意字符(包括空串),这样处理方式上完全改变,而且思路比较简单,先把通配符字符串组成部分分为两类:
- ******* ,连续的*,预处理的时候可以合并为一个*
- abc?d?,字母或?组合,后面都简写为X
考虑到第二类必须匹配才有可能整个字符串匹配,所以分两种情况考虑就可以了。
- 通配符字符串只有******或者X
- X*X*X或*X*X或者X*X*或者*X*这几种类型中的一种
对于第一种情况比较简单(略),第二种情况我是这样做的,先把通配符字符串两侧有的X匹配掉使得其只剩下 *X* 一种情况,接下来只要把所有X都找到匹配位置,则整个字符串匹配成功!
代码
//Runtime: 41 ms class Solution { public: bool fun(string s, string p){ if (s.length() != p.length()) return false; for (int i = 0; i < s.length(); i++){ if (s[i] == p[i] || p[i] == '?') continue; else return false; } return true; } bool isMatch(string s, string p) { int slen = s.length(); int plen = p.length(); vector<string> arr; if (!plen&&!slen) return true; if (!plen) return false; int single_count = 0; //预处理,将*******X****X****此类的串转为*X*X*的形式 for (int i = 0; i < plen; ){ if (p[i] == '*'){ string v = "*"; arr.push_back(v); i++; while (i < plen&&p[i] == '*') i++; } else{ string v; v += p[i]; i++; single_count++; while (i < plen&&p[i] != '*') { v+=p[i]; i++; single_count++; } arr.push_back(v); } } if (slen < single_count) return false; //这里的x,y均值的是包含字母或?的字符串 //情况一:y或* if (arr.size() == 1){ if (arr[0] == "*") return true; else return fun(s, arr[0]); } //情况二:y*x*x*y or y*x* or *x*y三种情况的y int left=0; int right = slen ; if (arr[0] != "*"){ int size = arr[0].size(); if (size > slen) return false; if(fun(s.substr(0, arr[0].size()), arr[0]) == false) return false; left = size; } if (arr.back() != "*"){ int size = arr.back().size(); if (size > slen) return false; if(fun(s.substr(slen - arr.back().length()), arr.back()) == false) return false; right = slen - size; arr.pop_back(); } int x = 1; while (x < arr.size()){ if (arr[x] != "*"){ int flag = 0; //标记是否在s以left开头的子串中是否有匹配项 while (left<right){ if (right - left < arr[x].length()) return false; //判断是否s有足够长度的串去匹配,没有则直接返回false if (fun(s.substr(left, arr[x].length()), arr[x])){ left += arr[x].length(); flag = 1; break; } else{ left++; } } if (!flag) return false; //如果没有找到任何匹配位置,则直接返回false } x++; } if (x == arr.size()) return true; //全部匹配则true return false; } };
时间: 2024-08-09 20:51:41