首页 > 其他 > 详细

[leetcode] Wildcard Matching

时间:2014-12-27 00:11:36      阅读:352      评论:0      收藏:0      [点我收藏+]

题目:(DP,BackTracking, Greedy,String)

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 express 那题很像,但是有区别。

首先要用贪心算法,就是两个string,一个char一个char的对比下去,

然后这题主要要分析的地方就是当*出现的时候,这时候要做的是s继续往后挪,看看能不能跟*后面的元素匹配上,能匹配上就继续往后对比。

public class Solution {
    public boolean isMatch(String s, String p) {
        int i=0;
        int j=0;
        int start=-1;
        int mark=-1;
        
        while(i<s.length())
        {
            if(j<p.length()&&
                 (s.charAt(i)==p.charAt(j)||p.charAt(j)==‘?‘))
            {
                ++i;
                ++j;
            }
            else if(j<p.length()&&p.charAt(j)==‘*‘)
            {
                start=j++;
                mark=i;
            }
            else if(start!=-1)
            {
                j=start+1;
                i=++mark;
            }
            else
            {
                return false;
            }
        }
        
        while(j<p.length()&&p.charAt(j)==‘*‘)
            j++;
        
        return j==p.length();
    }
}

 




[leetcode] Wildcard Matching

原文:http://www.cnblogs.com/fengmangZoo/p/4187708.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!