• [leetcode] Wildcard Matching


    题目:(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();
        }
    }



  • 相关阅读:
    AC_9. 分组背包问题
    AC_8. 二维费用的背包问题
    AC_7混合背包问题
    AC_5. 多重背包问题 II
    AC_4. 多重背包问题 I
    AC_3. 完全背包问题
    小郡肝火锅点餐系统——测试部署发布
    Vue脚手架搭建
    归并排序-总结
    小郡肝火锅点餐系统——项目文档
  • 原文地址:https://www.cnblogs.com/fengmangZoo/p/4187708.html
Copyright © 2020-2023  润新知