Wildcard Matching
来源:互联网 发布:局域网即时通讯软件 编辑:程序博客网 时间:2024/05/18 11:23
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
https://oj.leetcode.com/problems/wildcard-matching/
思路1:二维动归(提交竟然空间超出错误)。 dp[i][j]代表p[0...i]是否匹配 s[0...j]。
- 如果p[i]!='*',t[i][j] == true 当 t[i-1][j-1]==true &&(p[i]==s[j]||p[i]='.')
- 如果p[i]=='*',t[i][j]== true 当 其中一个m使得 t[i-1][m]==true,where 0<=m<j.
思路2:二维状态压缩为一维,原理是一样的。
publicclassSolution {
// MLE, the states can be compressed.
publicbooleanisMatchOld(String s, String p) {
if(s == null)
returnp == null;
if(p == null)
returns == null;
intm = p.length();
intn = s.length();
boolean[][] dp = newboolean[m + 1][n + 1];
dp[0][0] = true;
for(inti = 1; i <= m; i++) {
if(p.charAt(i - 1) == '*') {
intj = n + 1;
for(intk = 0; k <= n; k++) {
if(dp[i - 1][k])
j = k;
}
for(; j <= n; j++)
dp[i][j] = true;
}else{
for(intj = 1; j <= n; j++) {
if(dp[i - 1][j - 1]&& (p.charAt(i - 1) == s.charAt(j - 1) || p.charAt(i - 1) == '?'))
dp[i][j] = true;
}
}
dp[i][0] = dp[i - 1][0] && (p.charAt(i - 1) == '*');
}
returndp[m][n];
}
publicbooleanisMatch(String s, String p) {
if(s == null)
returnp == null;
if(p == null)
returns == null;
intm = p.length();
intn = s.length();
intcount = 0;
for(inti = 0; i < m; i++) {
if(p.charAt(i) != '*')
count++;
}
if(count > n)
returnfalse;
boolean[] dp = newboolean[n + 1];
dp[0] = true;
for(inti = 1; i <= m; i++) {
if(p.charAt(i - 1) == '*') {
intj = n+1;
for(intk = 0; k <= n; k++) {
if(dp[k]){
j = k;
break;
}
}
for(; j <= n; j++)
dp[j] = true;
}else{
for(intj = n; j >= 1; j--) {
dp[j]= (dp[j - 1]&& (p.charAt(i - 1) == s.charAt(j - 1) || p.charAt(i - 1) == '?'));
}
}
dp[0] = dp[0] && (p.charAt(i - 1) == '*');
}
returndp[n];
}
publicstaticvoid main(String[] args) {
System.out.println(newSolution().isMatch("ab","*a"));
}
}
- Wildcard Matching
- Wildcard Matching
- Wildcard Matching
- Wildcard Matching
- Wildcard Matching
- Wildcard Matching
- Wildcard Matching
- Wildcard Matching
- Wildcard Matching
- Wildcard Matching
- Wildcard Matching
- Wildcard Matching
- Wildcard matching
- Wildcard Matching
- Wildcard Matching
- Wildcard Matching
- Wildcard Matching
- Wildcard Matching
- 运算符号重载之自己转化为其它
- 几个不错的Shell脚本
- 2015元宵节礼物——《刀塔传奇》骨骼动画查看器,开源啦!
- Android 判断用户2G/3G/4G移动数据网络
- 记事本的一个bug
- Wildcard Matching
- Java 8新特性探究(八)精简的JRE详解
- VS2008重新编译OpenCV2.4.10动态库和静态库
- Java线程(八):锁对象Lock-同步问题更完美的处理方式
- CSDN博客自动访问
- dede(织梦)如何修改缩略图地址长度
- [BZOJ 1069][SCOI 2007]最大土地面积(凸包+旋转卡壳)
- 获取各种日期时间的总结
- Lucene+HighLighter 搜索关键字高亮显示