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



  • 相关阅读:
    计算机组成原理1.1.1 课程简介
    【Mybatis】配置文件加载属性
    【Maven】项目中没有resources目录
    C语言指针(三)指针传递给函数
    C语言指针(二)指向指针的指针
    C语言指针(一)
    cygwin环境c语言开发
    【Centos7】安装nginx
    【Linux】管理在线用户
    【总结】偏序/数点
  • 原文地址:https://www.cnblogs.com/fengmangZoo/p/4187708.html
Copyright © 2011-2022 走看看