leetcode--Wildcard Matching

来源:互联网 发布:json文件怎么打开 编辑:程序博客网 时间:2024/05/18 18:03

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


题意:

分类:动态规划,回溯,贪心,字符串


解法1:

[java] view plain copy
  1. public class Solution {  
  2.     public boolean isMatch(String s, String p) {  
  3.         int slen = s.length()+1;  
  4.         int plen = p.length()+1;  
  5.         boolean[][] dp = new boolean[slen][plen];  
  6.         dp[0][0]=true;  
  7.           
  8.         for(int i=1; i<plen; i++){  
  9.             if(p.charAt(i-1)=='*')  
  10.                 dp[0][i] = true;  
  11.             else  
  12.                 break;  
  13.         }  
  14.           
  15.         for(int i=1; i<slen; i++){  
  16.             for(int j=1; j<plen; j++){  
  17.                 if(p.charAt(j-1)=='*' && (dp[i-1][j] || dp[i][j-1] || dp[i-1][j-1]))  
  18.                     dp[i][j] = true;  
  19.                 else if(dp[i-1][j-1] && (p.charAt(j-1)=='?' || p.charAt(j-1)==s.charAt(i-1))){  
  20.                     dp[i][j] = true;  
  21.                 }  
  22.             }  
  23.         }  
  24.         return dp[slen-1][plen-1];  
  25.     }  
  26. }  


解法2:

[java] view plain copy
  1. if(p.length()==0)    
  2.         return s.length()==0;    
  3.     boolean[] res = new boolean[s.length()+1];    
  4.     res[0] = true;    
  5.     for(int j=0;j<p.length();j++)    
  6.     {    
  7.         if(p.charAt(j)!='*')    
  8.         {    
  9.             for(int i=s.length()-1;i>=0;i--)    
  10.             {    
  11.                 res[i+1] = res[i]&&(p.charAt(j)=='?'||s.charAt(i)==p.charAt(j));    
  12.             }    
  13.         }    
  14.         else    
  15.         {    
  16.             int i = 0;    
  17.             while(i<=s.length() && !res[i])    
  18.                 i++;    
  19.             for(;i<=s.length();i++)    
  20.             {    
  21.                 res[i] = true;    
  22.             }    
  23.         }    
  24.         res[0] = res[0]&&p.charAt(j)=='*';    
  25.     }    
  26.     return res[s.length()];  

原文链接http://blog.csdn.net/crazy__chen/article/details/47359779

原创粉丝点击