五月天青色头像情侣网名,国产亚洲av片在线观看18女人,黑人巨茎大战俄罗斯美女,扒下她的小内裤打屁股

歡迎光臨散文網 會員登陸 & 注冊

leetcode刷題筆記: 792 number-of-matching-subsequences

2022-11-18 08:57 作者:StepfenShawn  | 我要投稿

題目地址:

https://leetcode.cn/problems/number-of-matching-subsequences/


Given a string s and an array of strings words, return the number of words[i] that is a subsequence of s.

A subsequence of a string is a new string generated from the original string with some characters (can be none) deleted without changing the relative order of the remaining characters.

For example, "ace" is a subsequence of "abcde".

Example 1:

Input: s = "abcde", words = ["a","bb","acd","ace"]

Output: 3

Explanation: There are three strings in words that are a subsequence of s: "a", "acd", "ace".

Example 2:

Input: s = "dsahjpjauf", words = ["ahjpjau","ja","ahbwzgqnuk","tnmlanowax"]

Output: 2


題目大意

給定一個字符串數組words, 輸出元素為s的子序列的個數。

首先想到的是dp, 結果只過了21個用例, 復雜度極高:

能不能優(yōu)化一下呢? 又想到了雙指針, 比dp快了一點過了40多個用例,結果繼續(xù)超時。。。

由于s的數據長度范圍太大了, dp的方法貌似不太好優(yōu)化,那么我們先來優(yōu)化一下雙指針。

我們再看一下子序列的性質:?

A subsequence is a sequence that can be derived from an array by deleting some or no elements without changing the order of the remaining elements.

注意到假如c是s的子序列, 那么 c 的字符一定在 s 中, 這很顯然, 并且 c 的字符順序和 s 是相同的。

我們首先對 s 進行操作, 收集每個字符出現(xiàn)的位置并記錄在一個數組中。容易證明記錄出現(xiàn)位置的這個數組是排好序的(在for循環(huán)作用下單調遞增了),因此我們可以用二分查找進行優(yōu)化,只要保證二分查找后的位置比當前位置大, 那么該字符串就為s的子序列了:


leetcode刷題筆記: 792 number-of-matching-subsequences的評論 (共 條)

分享到微博請遵守國家法律
新津县| 同仁县| 广安市| 固阳县| 邯郸县| 同仁县| 普格县| 叶城县| 梧州市| 新化县| 蒲城县| 临沂市| 涿鹿县| 宾川县| 信丰县| 武强县| 遂宁市| 旌德县| 乌兰县| 长垣县| 龙海市| 临潭县| 河南省| 旬阳县| 吴江市| 玉溪市| 临澧县| 离岛区| 太和县| 施甸县| 盱眙县| 宜兴市| 攀枝花市| 奈曼旗| 会同县| 高台县| 庆元县| 万盛区| 尼木县| 南郑县| 探索|