zoukankan      html  css  js  c++  java
  • LeetCode

    题目:

    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
    
    思路:
    这题其实比Regular Expression Matching那道题容易,判断p中"*"的情况更简单。
    package dp;
    
    public class WildcardMatching {
    
        public boolean isMatch(String s, String p) {
            int slen = s.length();
            int plen = p.length();
            boolean[][] dp = new boolean[slen + 1][plen + 1];
            dp[0][0] = true;
            for (int i = 1; i <= plen; ++i)
                dp[0][i] = p.charAt(i - 1) == '*' ? dp[0][i - 1] : false;
            for (int i = 1; i <= slen; ++i)
                dp[i][0] = false;
            for (int i = 1; i <= slen; ++i) {
                for (int j = 1; j <= plen; ++j) {
                    if (p.charAt(j - 1) == '*') {
                        dp[i][j] = dp[i - 1][j - 1] || dp[i - 1][j] || dp[i][j - 1];
                    } else {
                        dp[i][j] = match(s.charAt(i - 1), p.charAt(j - 1)) && dp[i - 1][j - 1];
                    }
                }
            }
            
            return dp[slen][plen];
        }
        
        private boolean match(char a, char b) {
            if (b == '?' || b == '*')
                return true;
            return a == b;
        }
        
        public static void main(String[] args) {
            // TODO Auto-generated method stub
            WildcardMatching w = new WildcardMatching();
            System.out.println(w.isMatch("aa","a"));
            System.out.println(w.isMatch("aa","aa"));
            System.out.println(w.isMatch("aaa","aa"));
            System.out.println(w.isMatch("aa", "*"));
            System.out.println(w.isMatch("aa", "a*"));
            System.out.println(w.isMatch("ab", "?*"));
            System.out.println(w.isMatch("aab", "c*a*b"));
            
        }
    
    }
  • 相关阅读:
    用servlet来实现验证码的功能
    Sqlite3 数据库
    xml解析
    Android .9文件
    AsyncTask
    Looper Handler
    URLConnection
    单例模式
    Httpclient访问网络
    json 解析
  • 原文地址:https://www.cnblogs.com/null00/p/5075544.html
Copyright © 2011-2022 走看看