zoukankan      html  css  js  c++  java
  • [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();
        }
    }



  • 相关阅读:
    经典8锁问题--助你彻底搞懂锁的概念
    linux上安装mysql
    Jenkins安装详解
    第一篇:实时网络日志分析器和交互式查看器--GoAccess安装
    Centos7上安装python3.7
    Nginx报错收集
    免费yum源镜像地址
    nginx日志文件切割
    腾讯云绑定和配置弹性网卡和添加弹性网卡
    LNMP-WEB应用环境搭建
  • 原文地址:https://www.cnblogs.com/fengmangZoo/p/4187708.html
Copyright © 2011-2022 走看看