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 MatchingCheck if an Original String Exists Given Two Encoded Strings.

posted @ 2015-11-10 12:30  Dylan_Java_NYC  阅读(301)  评论(0编辑  收藏  举报