最美情侣中文字幕电影,在线麻豆精品传媒,在线网站高清黄,久久黄色视频

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

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的評論 (共 條)

分享到微博請遵守國家法律
绥宁县| 白沙| 汪清县| 江都市| 邢台县| 沂水县| 山西省| 濮阳市| 房产| 鹤岗市| 都昌县| 松滋市| 博客| 康保县| 钟祥市| 苗栗县| 廉江市| 永宁县| 灵璧县| 屏东市| 绥棱县| 日土县| 海淀区| 延庆县| 同仁县| 左贡县| 贡嘎县| 四会市| 白朗县| 彰武县| 肥西县| 平安县| 永城市| 竹溪县| 资兴市| 黄大仙区| 舒城县| 环江| 阜宁县| 根河市| 铅山县|