package com.isMatch;
import org.junit.Test;
/**
* 给定一个字符串 (s) 和一个字符模式 (p) ,实现一个支持 '?' 和 '*' 的通配符匹配。
*
* '?' 可以匹配任何单个字符。
* '*' 可以匹配任意字符串(包括空字符串)。
* 两个字符串完全匹配才算匹配成功。
*
* 说明:
*
* s 可能为空,且只包含从 a-z 的小写字母。
* p 可能为空,且只包含从 a-z 的小写字母,以及字符 ? 和 *。
*
* 来源:力扣(LeetCode)
* 链接:https://leetcode-cn.com/problems/wildcard-matching
* 著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。
*/
public class IsMatch {
Boolean[][] result;
/**
* 解题思路:画二维表,我开始的想法有些笨拙(相对于答案来说),我的想法是将字符串p看作x轴,s作为y轴,
* 这样导致出现空字符串的时候不好处理。我们可以在p和s字符串前面加一个空字符,这样就好解决多了。
* 另一种算法参考之前写过的。或者看答案
* @param s
* @param p
* @return
*/
public boolean isMatch(String s, String p) {
// 初始化操作
int x = s.length();
int y = p.length();
if (x == 0) {
if (p.replace("*","").length() != 0) {
return false;
} else {
return true;
}
} else if (y == 0) {
return false;
}
result = new Boolean[x][y];
int q = 0;
while (q < y) {
if (p.charAt(q) == '*') {
result[0][q] = true;
} else {
break;
}
q++;
}
if (p.charAt(q) == s.charAt(0)) {
result[0][q] = true;
q++;
}
while (q < y) {
if (p.charAt(q) == '*') {
result[0][q] = true;
} else {
break;
}
q++;
}
for (int i = q; i < y; i++) {
result[0][i] = false;
}
for (int i = 1; i < x; i++) {
for (int j = 0; j < y; j++) {
result[i][j] = false;
if (p.charAt(j) == '*') {
for (int k = 0; k <= i; k++) {
if (j < 1 || result[k][j - 1]) {
result[i][j] = true;
break;
}
}
} else if (j > 0 && result[i - 1][j - 1]) {
if (p.charAt(j) == s.charAt(i) || p.charAt(j) == '?') {
result[i][j] = true;
}
} else {
result[i][j] = false;
}
}
}
return result[x - 1][y - 1];
}
@Test
public void test() {
// System.out.println(isMatch("acdcb", "a*c?b"));
System.out.println(isMatch("adceb", "*a*b"));
}
}
动态规划字符串匹配
最新推荐文章于 2023-01-28 16:53:01 发布