leetcode----Wildcard Matching

来源:互联网 发布:linux 批量压缩文件夹 编辑:程序博客网 时间:2024/05/16 09:27
'?' 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") → falseisMatch("aa","aa") → trueisMatch("aaa","aa") → falseisMatch("aa", "*") → trueisMatch("aa", "a*") → trueisMatch("ab", "?*") → true

isMatch("aab", "c*a*b") → false

?字符能够匹配任何的单个字符

*能够匹配一个任意长度的字符串 包括空字符串

根据题意我们可以设想到 p字符串中除去*字符串 p的长度一定会比s字符串的长度短。

所以在测试的过程中,当s字符串遍历结束的时候就是整个测试的结束,当然,在这过程中如果遇到不符合题意的情况 会提前结束遍历

我们采用贪心算法实现如下:

public class Solution {  public boolean isMatch(String s, String p) {    if (s == null || p == null) return false;//输入的字符串任何一项为null就退出  结束测试。    if (s.equals(p)) return true;//两个字符串完全相等  不存在*?匹配问题。直接输出    int m = s.length();//s字符串的长度    int n = p.length();//p字符串的长度    int posS = 0;//s字符串检测的当前位置    int posP = 0;//p字符串检测的当前位置    int posStar = -1;//在检测的过程中P字符串出现*  就记录当前s字符串当前的位置    int posOfS = -1;//<span style="line-height: 18.5714282989502px; font-family: Menlo, Monaco, Consolas, 'Courier New', monospace;">在检测的过程中P字符串出现*  就记录当前p字符串当前的位置</span>    //if posS == posP || posP == '?', ++posS and ++posP.    //posOfS, posStar, record the positon of '*' in s and p, ++posP and go on.    //if not match, go back to star, ++posOfS    while (posS < m) {  //当前的位置要小于S字符串的长度      if (posP < n && (s.charAt(posS) == p.charAt(posP) || p.charAt(posP) == '?')) {//在当前位置字符串p,s对应的位置相等的时候或者p字符串是问号字符时        ++posS;//累加        ++posP;      }      else if (posP < n && p.charAt(posP) == '*') {//当前p的字符时*时        posStar = posP;//记录遍历的位置p        posOfS = posS;//记录遍历的位置s        ++posP;//P当前位置向前移一个        continue;      }      else if (posStar != -1) {//posStar是为起一个辨别的作用  当p中有*时  posStar!=-1  这里的处理很重要  *可以对应一个字符串,对应的字符串的长度是未知的,所以要逐个移动匹配的起始点   第一个起始点就是s不动  p位置在*字符基础上向后移动一个位置  以此类推  直到有匹配了  就Ok了  这里要好好看看好好想想        posS = posOfS;        posP = posStar + 1;        ++posOfS;      }      else {        return false;      }    }    while (posP < n && p.charAt(posP) == '*') {      ++posP;  //s匹配结束  当p字符串后面都是*时    }      return posS == m && posP == n;  }}
这个题目比较好 折腾了我很长时间 上面的程序也不是我想出来的 唉。。。网上高手真多啊

0 0
原创粉丝点击