天题系列: Wildcard Matching

题解抄自“http://simpleandstupid.com/2014/10/26/wildcard-matching-leetcode-%E8%A7%A3%E9%A2%98%E7%AC%94%E8%AE%B0/”

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

Leetcode中最难的题之一,不过很多人onsite还是遇到了这道题,所以还是有必要掌握的。
一个比较好的算法是贪心算法(greedy): whenever encounter ‘*’ in p, keep record of the current position of ‘*’ in p and the current index in s. Try to match the stuff behind this ‘*’ in p with s, if not matched, just s++ and then try to match again.

public class Solution {
    public boolean isMatch(String s, String p) {
         int star = -1, mark=-1, i=0, j=0;
         while(i<s.length()){
             // if matched , both move on
             if(j<p.length() && (p.charAt(j)=='?'||p.charAt(j)==s.charAt(i))){
                 i++;
                 j++;
            // if a star was found, put mark to i, star to j, move j to next
             }else if(j<p.length() && p.charAt(j)=='*'){
                 mark = i;
                 star = j++;
            // if there was star#>=1, but nothing matched,  则继续比较s中的下一个字符 :put j back to star's next position, move i to next, move mark to next(greedy, must check s 1by1)
             }else if(star!=-1){
                 j = star+1;
                 i = ++mark;
            // no star, nothing matched
             }else
                return false;
         }
        //最后在此处处理多余的‘*’,因为多个‘*’和一个‘*’意义相同。
         while(j<p.length() && p.charAt(j)=='*'){
             j++;
         }
         return j==p.length() ;
    }
}

 

posted @ 2015-06-02 06:52  世界到处都是小星星  阅读(159)  评论(0编辑  收藏  举报