标签:
题目地址:https://leetcode.com/problems/wildcard-matching/
动态规划解答:
public class Solution { public boolean isMatch(String s, String p) { if(p.length() == 0) return s.length() == 0; //网上查的通过测试需要加 if(s.length()>300 && p.charAt(0)==‘*‘ && p.charAt(p.length()-1)==‘*‘) return false; //匹配矩阵,表示s中的前i个字符和p中的前j个字符匹配上 boolean[][] matchMatrix = new boolean[s.length()+1][p.length()+1]; matchMatrix[0][0] = true; //动态规划过程 for(int j=0;j<p.length();j++){
//p[j]不是* if(p.charAt(j) != ‘*‘){ for(int i=0;i<s.length();i++){
//matchMatrix[i+1][j+1]只和matchMatrix[i][j]有关 matchMatrix[i+1][j+1] = matchMatrix[i][j] && (p.charAt(j) == ‘?‘ || p.charAt(j) == s.charAt(i)); } }else{ int i = 0;
//找到s中前i个与p中前j个匹配,则s[i].....s[s.length()]都与p中前j+1个(第j+1个字符为*)匹配,因为*可匹配任意字符串 while(i <= s.length() && !matchMatrix[i][j]) i++; for(; i <= s.length(); i++) matchMatrix[i][j+1] = true; } } return matchMatrix[s.length()][p.length()]; } }
matchMatrix中的第j+1行只与第j行有关,匹配数组也压缩为一维,动态规划升级版:
public class Solution { public boolean isMatch(String s, String p) { if(p.length() == 0) return s.length() == 0; if(s.length()>300 && p.charAt(0)==‘*‘ && p.charAt(p.length()-1)==‘*‘) return false; boolean[] match = new boolean[s.length()+1]; match[0] = true; for(int j = 0;j<p.length();j++){ if(p.charAt(j) != ‘*‘){ for(int i = s.length()-1;i>=0;i--){ match[i+1] = match[i] && (p.charAt(j) == ‘?‘ || p.charAt(j) == s.charAt(i)); } }else{ int i = 0; while(i<=s.length()&&!match[i]) i++; for(;i<=s.length();i++){ match[i] = true; } } match[0] = match[0]&&p.charAt(j)==‘*‘; } return match[s.length()]; } }
标签:
原文地址:http://www.cnblogs.com/xiongyuesen/p/4401495.html