LeetCode #44
来源:互联网 发布:刺客信条大革命1.5优化 编辑:程序博客网 时间:2024/06/07 03:31
题目描述:
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") → falseisMatch("aa","aa") → trueisMatch("aaa","aa") → falseisMatch("aa", "*") → trueisMatch("aa", "a*") → trueisMatch("ab", "?*") → trueisMatch("aab", "c*a*b") → false
class Solution {public: bool isMatch(string s, string p) { p=continuous_star(p); if(s.size()==0&&p.size()==0) return true; else if(s.size()!=0&&p.size()==0) return false; else if(s.size()==0&&p[0]=='*') return isMatch(s,p.substr(1)); else if(s.size()==0&&p[0]!='*') return false; else if(s.size()!=0&&p.size()!=0) { if(p[0]!='*') { if(p[0]==s[0]||p[0]=='?') return isMatch(s.substr(1),p.substr(1)); else return false; } else if(p[0]=='*') { if(isMatch(s,p.substr(1))) return true; else return isMatch(s.substr(1),p); } } } string continuous_star(string p) { for(int i=1;i<p.size();i++) { if(p[i-1]=='*'&&p[i]=='*') p=p.erase(i,1); } return p; }};
为了减少运行时间,采用动态规划的方法,对于二维数组的初始化方式和递推方法都和之前正则表达式匹配有所不同,而且相对更简单一点:①将两个字符串首部添加空格字符,并对二维数组首行和首列进行初始化,便于递推。②1、当p[j]不为‘*’,则p[j]必须等于s[i],否则不能匹配。2、当p[j]为‘*’时,p[j]可以匹配任意长度的字符串,所以当x[i][j-1]为真,x[i][j]也为真,此时p[j]表示空字符串;同时如果x[i-1][j]为真时,x[i][j]也为真,即p[j]匹配的字符串增加一位,将s[i]也包括进去。递推结束后返回x[n-1][m-1]。
class Solution {public: bool isMatch(string s, string p) { s=" "+s; p=" "+p; int m=s.size(); int n=p.size(); bool x[m][n]; x[0][0]=true; for(int i=1;i<m;i++) { x[i][0]=false; } for(int j=1;j<n;j++) { if(x[0][j-1]==true&&p[j]=='*') x[0][j]=true; else x[0][j]=false; } for(int i=1;i<m;i++) { for(int j=1;j<n;j++) { if(p[j]!='*') { if((p[j]==s[i]||p[j]=='?')&&x[i-1][j-1]==true) x[i][j]=true; else x[i][j]=false; } else if(p[j]=='*') { if(x[i][j-1]==true) x[i][j]=true; else if(x[i-1][j]==true) x[i][j]=true; else x[i][j]=false; } } } return x[m-1][n-1]; }};
阅读全文
0 0
- Leetcode#44||
- leetcode 44
- LeetCode #44
- leetcode 44: 4Sum
- LeetCode(44)Permutations
- LeetCode(44) Wildcard Matching
- [leetcode] 44 Wildcard Matching
- LeetCode 44:Wildcard Matching
- leetcode 44: Wildcard Matching
- leetcode 44: Wildcard Matching
- [leetcode 44] Wildcard Matching
- leetcode 44:Wildcard Matching
- LeetCode 44 - Wildcard Matching
- LeetCode(44)- Isomorphic Strings
- leetcode #44 in cpp
- leetcode 44 Wildcard Matching
- LeetCode OJ-44-Permutations
- LeetCode(44) Wildcard Matching
- Shell编程基础
- javascript之多态
- tcp协议,ip协议,http协议三者的关系,从发起一个http url例子来分析
- 滴滴---2017校招---后台开发面经
- STM32学习笔记之时钟分析(受启发有汲取之处)
- LeetCode #44
- C 语言学习笔记01:变量存储方式和存储类别
- 算法课程Leetcode作业第二周技术博客
- Java 内存管理机制,深入理解JVM
- 循环输入和输出二维字符数组
- Sublime Text3开发快捷键(Windows)
- TypeError: object() takes no parameters
- 读书笔记:《演讲的力量(干货版)》
- 【Oracle】NLS_LANG详解