您的位置:首页 > 其它

LeetCode Wildcard Matching

2015-11-10 12:30 330 查看
原题链接在这里: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

DP. dp[i][j]表示长度为i的s 和长度为j 的p是否match.

若不match 且 p.charAt(j) == '*'. 若*代表0个char, dp[i][j] = dp[i][j-1].

  若*代表1 个char dp[i][j] = dp[i-1][j]. 若 * 代表2个char dp[i][j] = dp[i-2][j]. 一直到头.

  多以dp[i][j] = dp[i][j-1] || dp[i-1][j] || dp[i-2][j] || ... || dp[0][j]

  因为j是从1到n方向更新。所以后半部分可以直接用dp[i-1][j]表示。

当s.charAt(i) match p.charAt(j)时 dp[i][j] = dp[i-1][j-1].

Time Complexity: O(m*n). Space: O(m*n).

AC Java:

public class Solution {
public boolean isMatch(String s, String p) {
int m = s.length();
int n = p.length();
boolean [][] dp = new boolean[m+1][n+1];
dp[0][0] = true;
for(int j = 1; j<=n; j++){
if(p.charAt(j-1) == '*'){
dp[0][j] = true;
}else{
break;
}
}

for(int i = 1; i<=m; i++){
for(int j = 1; j<=n; j++){
if(p.charAt(j-1) == '*'){
dp[i][j] = dp[i][j-1] || dp[i-1][j];
}else if(s.charAt(i-1) == p.charAt(j-1) || p.charAt(j-1) == '?'){
dp[i][j] = dp[i-1][j-1];
}
}
}
return dp[m]
;
}
}


双指针,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:

public class Solution {
public boolean isMatch(String s, String p) {
if(p.length() == 0){
return s.length() == 0;
}
int starIndex = -1; //标记星号的index
int lastCheck = -1; //标记上次检查的位置

int i = 0;
int j = 0;
while(i<s.length()){
if(j<p.length() && isMatch(s.charAt(i), p.charAt(j))){
i++;
j++;
}else if(j<p.length() && p.charAt(j) == '*'){
starIndex = j;
lastCheck = i;
j++;
}else if(starIndex != -1){
j = starIndex+1;
lastCheck++;
i=lastCheck;
}else{
return false;
}
}
//s = "", p = "**"
while(j<p.length() && p.charAt(j) == '*'){
j++;
}
return j == p.length();
}

private boolean isMatch(char s, char p){
return p == '?' || s == p;
}
}


Ref: /article/5590712.html
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: