• LeetCode 44. Wildcard Matching


    原题链接在这里:https://leetcode.com/problems/wildcard-matching/

    题目:

    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

    题解:

    双指针,i为s的index, j为p的index.

    i 小于 s.length() 前提下检查 s.charAt(i) 和 p.charAt(j)是否match. 若是当前对应字符match, 双双后移一位。

    若是不能match且p的当前字符是'*', 就更新星号的starIndex 和 最后检查的位置lastCheck. 

    当再次遇到不match时,j回到startIndex的后一位,lastCheck后一一位,i到lastCheck位上.

    出了while loop 说明s到头了,看j是否到头即可。但是若当前j是'*', 需要一致后移j.

    Time Complexity: O(s.length() * p.length()).

    Space: O(1).

    AC Java:

     1 public class Solution {
     2     public boolean isMatch(String s, String p) {
     3         if(p.length() == 0){
     4             return s.length() == 0;
     5         }
     6         int starIndex = -1; //标记星号的index
     7         int lastCheck = -1; //标记上次检查的位置
     8         
     9         int i = 0; 
    10         int j = 0;
    11         while(i<s.length()){
    12             if(j<p.length() && isMatch(s.charAt(i), p.charAt(j))){
    13                 i++;
    14                 j++;
    15             }else if(j<p.length() && p.charAt(j) == '*'){
    16                 starIndex = j;
    17                 lastCheck = i;
    18                 j++;
    19             }else if(starIndex != -1){
    20                 j = starIndex+1;
    21                 lastCheck++;
    22                 i=lastCheck;
    23             }else{
    24                 return false;
    25             }
    26         }
    27         //s = "", p = "**"
    28         while(j<p.length() && p.charAt(j) == '*'){
    29             j++;
    30         }
    31         return j == p.length();
    32     }
    33     
    34     private boolean isMatch(char s, char p){
    35         return p == '?' || s == p;
    36     }
    37 }

    类似Regular Expression Matching.

  • 相关阅读:
    全角半角转换
    MSN的头像存放路径
    treeview托拽和动态添加节点以及treeview和xml的交互的实现
    一个简单的分页存储过程
    datagrid数据导出到excel文件给客户端下载的几种方法
    大容量数据传输,web.config修改方法
    XSD(XML Schema Definition)学习笔记
    最近想发起一次服务器合租,有米有人有兴趣
    从首页看CCS布局
    关于CS1.1后台管理页面的研究
  • 原文地址:https://www.cnblogs.com/Dylan-Java-NYC/p/4952497.html
Copyright © 2020-2023  润新知