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") → false
isMatch("aa","aa") → true
isMatch("aaa","aa") → false
isMatch("aa", "*") → true
isMatch("aa", "a*") → true
isMatch("ab", "?*") → true
isMatch("aab", "c*a*b") → false
题意:
分类:动态规划,回溯,贪心,字符串
解法1:
- public class Solution {
- public boolean isMatch(String s, String p) {
- int slen = s.length()+1;
- int plen = p.length()+1;
- boolean[][] dp = new boolean[slen][plen];
- dp[0][0]=true;
-
- for(int i=1; i<plen; i++){
- if(p.charAt(i-1)=='*')
- dp[0][i] = true;
- else
- break;
- }
-
- for(int i=1; i<slen; i++){
- for(int j=1; j<plen; j++){
- if(p.charAt(j-1)=='*' && (dp[i-1][j] || dp[i][j-1] || dp[i-1][j-1]))
- dp[i][j] = true;
- else if(dp[i-1][j-1] && (p.charAt(j-1)=='?' || p.charAt(j-1)==s.charAt(i-1))){
- dp[i][j] = true;
- }
- }
- }
- return dp[slen-1][plen-1];
- }
- }
解法2:
- if(p.length()==0)
- return s.length()==0;
- boolean[] res = new boolean[s.length()+1];
- res[0] = true;
- for(int j=0;j<p.length();j++)
- {
- if(p.charAt(j)!='*')
- {
- for(int i=s.length()-1;i>=0;i--)
- {
- res[i+1] = res[i]&&(p.charAt(j)=='?'||s.charAt(i)==p.charAt(j));
- }
- }
- else
- {
- int i = 0;
- while(i<=s.length() && !res[i])
- i++;
- for(;i<=s.length();i++)
- {
- res[i] = true;
- }
- }
- res[0] = res[0]&&p.charAt(j)=='*';
- }
- return res[s.length()];
原文链接http://blog.youkuaiyun.com/crazy__chen/article/details/47359779