leetcode44-通配符匹配
- dp
和正则匹配方法类似。先去处理边界值为0的情况。dp[0][0] = true
,同时让j从0到n开始遍历,如果当前的位置是,那么dp[0][j] = true
,因为可以匹配0个字符,否则表明无法继续零匹配,直接跳出循环。
然后进行二维循环,如果当前的匹配串为*,那么有两种选择,匹配之前的字符或者零匹配。如果当前的字符为?,那么可以进行一次匹配,否则,需要看匹配串和原字符串的字符是否相等,且依赖于dp[i-1][j-1]
的状态
class Solution {
public boolean isMatch(String s, String p) {
int m = s.length(), n = p.length();
boolean dp[][] = new boolean[m+1][n+1];
dp[0][0] = true;
for(int j = 1; j <= n; j++){
if(p.charAt(j-1) == '*') dp[0][j] = true;
else break;
}
for(int i = 1; i <= m; i++){
for(int j = 1; j <= n; j++){
if(p.charAt(j-1) == '*') dp[i][j] = dp[i-1][j] || dp[i][j-1];
else dp[i][j] = dp[i-1][j-1] && (p.charAt(j-1) == '?' || s.charAt(i-1) == p.charAt(j-1));
}
}
return dp[m][n];
}
}
- 贪心
class Solution {
public boolean isMatch(String s, String p) {
int sRight = s.length(), pRight = p.length();
while (sRight > 0 && pRight > 0 && p.charAt(pRight - 1) != '*') {
if (charMatch(s.charAt(sRight - 1), p.charAt(pRight - 1))) {
--sRight;
--pRight;
} else {
return false;
}
}
if (pRight == 0) {
return sRight == 0;
}
int sIndex = 0, pIndex = 0;
int sRecord = -1, pRecord = -1;
while (sIndex < sRight && pIndex < pRight) {
//如果p当前位置是*,那么跳过这个字符,进行标记,继续匹配
if (p.charAt(pIndex) == '*') {
++pIndex;
sRecord = sIndex;
pRecord = pIndex;
} else if (charMatch(s.charAt(sIndex), p.charAt(pIndex))) { //如果能匹配,继续进行
++sIndex;
++pIndex;
} else if (sRecord != -1 && sRecord + 1 < sRight) { //如果匹配不了并且这个字符不是p的最后一个字符(最后一个字符可以用sRight的*来匹配),那么寻找下一个*起始的位置(之前用sRecord标记
++sRecord;
sIndex = sRecord;
pIndex = pRecord;
} else {
return false;
}
}
return allStars(p, pIndex, pRight);
}
public boolean allStars(String str, int left, int right) {
for (int i = left; i < right; ++i) {
if (str.charAt(i) != '*') {
return false;
}
}
return true;
}
public boolean charMatch(char u, char v) {
return u == v || v == '?';
}
}
本文作者:xzh-yyds
本文链接:https://www.cnblogs.com/xzh-yyds/p/16599221.html
版权声明:本作品采用知识共享署名-非商业性使用-禁止演绎 2.5 中国大陆许可协议进行许可。
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 单线程的Redis速度为什么快?
· 展开说说关于C#中ORM框架的用法!
· 阿里最新开源QwQ-32B,效果媲美deepseek-r1满血版,部署成本又又又降低了!
· Pantheons:用 TypeScript 打造主流大模型对话的一站式集成库
· SQL Server 2025 AI相关能力初探