日韩性视频-久久久蜜桃-www中文字幕-在线中文字幕av-亚洲欧美一区二区三区四区-撸久久-香蕉视频一区-久久无码精品丰满人妻-国产高潮av-激情福利社-日韩av网址大全-国产精品久久999-日本五十路在线-性欧美在线-久久99精品波多结衣一区-男女午夜免费视频-黑人极品ⅴideos精品欧美棵-人人妻人人澡人人爽精品欧美一区-日韩一区在线看-欧美a级在线免费观看

歡迎訪問(wèn) 生活随笔!

生活随笔

當(dāng)前位置: 首頁(yè) > 编程资源 > 编程问答 >内容正文

编程问答

[LintCode] Wildcard Matching

發(fā)布時(shí)間:2025/4/9 编程问答 19 豆豆
生活随笔 收集整理的這篇文章主要介紹了 [LintCode] Wildcard Matching 小編覺(jué)得挺不錯(cuò)的,現(xiàn)在分享給大家,幫大家做個(gè)參考.

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).

Example 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

?

SOLUTION:

通配符匹配,很像Distinct Subsequences的思維方式。像這樣給倆字串,然后看true or false的,基本DP可以用。既然給了倆字傳,那就先不考慮優(yōu)化問(wèn)題,先開(kāi)個(gè)二維空間記錄結(jié)果。

狀態(tài):f(i , j) 表示S前i個(gè)跟T前j個(gè)可以不可以匹配。

方程:情況1. T(j) == ? || T(j) == S(i) (因?yàn)檫@兩種情況都是匹配一個(gè)字符,所以放在一起)這時(shí)候 f(i, j) = f(i - 1, j - 1)。就是說(shuō)T(j)必須去匹配,不然這個(gè)字母沒(méi)意義了。

? ? ? ? ?情況2. T(j) == *,這時(shí)候*匹配任意字符,所以呢,f(i, j ) =f(i, j - 1) || f(i - 1, j - 1) || f(i - 2, j - 1) || f(i - 3, j - 1) ... ... || f(1, j - 1):意思就是說(shuō),S(i) 之前包括S(i)本身,只要有任意一個(gè)跟T(*)前面的一個(gè)字符匹配上,就可以。

   ? 看起來(lái)很麻煩,但是,仔細(xì)看,這個(gè)公式可以簡(jiǎn)化:因?yàn)閒(i - 1, j) = f(i - 1, j - 1) || f(i - 2, j - 1) || ... ... || f(1, j - 1), 所以上面f(i , j) ?= f(i , j - 1) || f ( i - 1, j) 。

   通俗的說(shuō),就是,在當(dāng)時(shí)這一dp層去考慮,我可以用*匹配 f (i - 1, j) ,也可以不用*去匹配 f (i, j - 1)。

初始化:f(0, 0 )用方程推不出,所以要單獨(dú)考慮。 f(0,0) = true 意思就是null匹配null。

代碼如下:

public class Solution {/*** @param s: A string * @param p: A string includes "?" and "*"* @return: A boolean*/// f(i, j) if p(j) = ? || p(j) == s(i) ==>f(i,j) = f(i - 1, j - 1)// if p(j) = * ==> f(i,j) = f(i - 1, j) f(i, j - 1)public boolean isMatch(String s, String p) {if (s == null){return p == null;}if (p == null){return s == null;}boolean[][] result = new boolean[s.length() + 1][p.length() + 1];result[0][0] = true;for (int i = 1; i <= s.length(); i++){for (int j = 1; j <= p.length(); j++){if (result[0][j - 1] && p.charAt(j - 1) == '*'){result[0][j] = true;}if (p.charAt(j - 1) == s.charAt(i - 1) || p.charAt(j - 1) == '?'){result[i][j] = result[i - 1][j - 1];}if (p.charAt(j - 1) == '*'){result[i][j] = (result[i - 1][j] || result[i][j - 1]);}}}return result[s.length()][p.length()];} } View Code

?

轉(zhuǎn)載于:https://www.cnblogs.com/tritritri/p/4957759.html

總結(jié)

以上是生活随笔為你收集整理的[LintCode] Wildcard Matching的全部?jī)?nèi)容,希望文章能夠幫你解決所遇到的問(wèn)題。

如果覺(jué)得生活随笔網(wǎng)站內(nèi)容還不錯(cuò),歡迎將生活随笔推薦給好友。