• 792. 匹配子序列的单词数 : 常规预处理优化匹配过程


    题目描述

    这是 LeetCode 上的 792. 匹配子序列的单词数 ,难度为 中等

    Tag : 「二分」、「哈希表

    给定字符串 s 和字符串数组 words, 返回  words[i] 中是 s 的子序列的单词个数 。

    字符串的 子序列 是从原始字符串中生成的新字符串,可以从中删去一些字符(可以是""),而不改变其余字符的相对顺序。

    例如, “ace” 是 “abcde” 的子序列。

    示例 1:

    1. 输入: s = "abcde", words = ["a","bb","acd","ace"]
    2. 输出: 3
    3. 解释: 有三个是 s 的子序列的单词: "a", "acd", "ace"
    4. 复制代码

    示例 2:

    1. 输入: s = "dsahjpjauf", words = ["ahjpjau","ja","ahbwzgqnuk","tnmlanowax"]
    2. 输出: 2
    3. 复制代码

    提示:

    • 1 <= s.length <= 5 \times 10^41<=s.length<=5×104
    • 1 <= words.length <= 50001<=words.length<=5000
    • 1 <= words[i].length <= 501<=words[i].length<=50
    • words[i] 和 s 都只由小写字母组成。

    预处理 + 哈希表 + 二分

    朴素判定某个字符串是为另一字符串的子序列的复杂度为 O(n + m)O(n+m),对于本题共有 50005000 个字符串需要判定,每个字符串最多长为 5050,因此整体计算量为 (5 \times 10^4 + 50) \times 5000 \approx 2.5 \times 10^8(5×104+50)×5000≈2.5×108,会超时。

    不可避免的是,我们要对每个 words[i]words[i] 进行检查,因此优化的思路可放在如何优化单个 words[i]words[i] 的判定操作。

    朴素的判定过程需要使用双指针扫描两个字符串,其中对于原串的扫描,会有大量的字符会被跳过(无效匹配),即只有两指针对应的字符相同时,匹配串指针才会后移。

    我们考虑如何优化这部分无效匹配。

    对于任意一个 w = words[i]w=words[i] 而言,假设我们当前匹配到 w[j]w[j] 位置,此时我们已经明确下一个待匹配的字符为 w[j + 1]w[j+1],因此我们可以直接在 s 中字符为 w[j + 1]w[j+1] 的位置中找候选。

    具体的,我们可以使用哈希表 map 对 s 进行预处理:以字符 c = s[i]c=s[i] 为哈希表的 key,对应的下标 ii 集合为 value,由于我们从前往后处理 s 进行预处理,因此对于所有的 value 均满足递增性质。

    举个 🌰 : 对于 s = abcabc 而言,预处理的哈希表为 {a=[0,3], b=[1,4], c=[2,5]}

    最后考虑如何判定某个 w = words[i]w=words[i] 是否满足要求:待匹配字符串 w 长度为 m,我们从前往后对 w 进行判定,假设当前判待匹配位置为 w[i]w[i],我们使用变量 idx 代表能够满足匹配 w[0:i]w[0:i] 的最小下标(贪心思路)。

    对于匹配的 w[i]w[i] 字符,可以等价为在 map[w[i]] 中找到第一个大于 idx 的下标,含义在原串 s 中找到字符为 w[i] 且下标大于 idx 的最小值,由于我们所有的 map[X] 均满足单调递增,该过程可使用「二分」进行。

    Java 代码:

    1. class Solution {
    2. public int numMatchingSubseq(String s, String[] words) {
    3. int n = s.length(), ans = 0;
    4. Map<Character, List<Integer>> map = new HashMap<>();
    5. for (int i = 0; i < n; i++) {
    6. List<Integer> list = map.getOrDefault(s.charAt(i), new ArrayList<>());
    7. list.add(i);
    8. map.put(s.charAt(i), list);
    9. }
    10. for (String w : words) {
    11. boolean ok = true;
    12. int m = w.length(), idx = -1;
    13. for (int i = 0; i < m && ok; i++) {
    14. List<Integer> list = map.getOrDefault(w.charAt(i), new ArrayList<>());
    15. int l = 0, r = list.size() - 1;
    16. while (l < r) {
    17. int mid = l + r >> 1;
    18. if (list.get(mid) > idx) r = mid;
    19. else l = mid + 1;
    20. }
    21. if (r < 0 || list.get(r) <= idx) ok = false;
    22. else idx = list.get(r);
    23. }
    24. if (ok) ans++;
    25. }
    26. return ans;
    27. }
    28. }
    29. 复制代码

    TypeScript 代码:

    1. function numMatchingSubseq(s: string, words: string[]): number {
    2. let n = s.length, ans = 0
    3. const map = new Map<String, Array<number>>()
    4. for (let i = 0; i < n; i++) {
    5. if (!map.has(s[i])) map.set(s[i], new Array<number>())
    6. map.get(s[i]).push(i)
    7. }
    8. for (const w of words) {
    9. let ok = true
    10. let m = w.length, idx = -1
    11. for (let i = 0; i < m && ok; i++) {
    12. if (!map.has(w[i])) {
    13. ok = false
    14. } else {
    15. const list = map.get(w[i])
    16. let l = 0, r = list.length - 1
    17. while (l < r) {
    18. const mid = l + r >> 1
    19. if (list[mid] > idx) r = mid
    20. else l = mid + 1
    21. }
    22. if (r < 0 || list[r] <= idx) ok = false
    23. else idx = list[r]
    24. }
    25. }
    26. if (ok) ans++
    27. }
    28. return ans
    29. }
    30. 复制代码

    Python3 代码:

    1. class Solution:
    2. def numMatchingSubseq(self, s: str, words: List[str]) -> int:
    3. dmap = defaultdict(list)
    4. for i, c in enumerate(s):
    5. dmap[c].append(i)
    6. ans = 0
    7. for w in words:
    8. ok = True
    9. idx = -1
    10. for i in range(len(w)):
    11. idxs = dmap[w[i]]
    12. l, r = 0, len(idxs) - 1
    13. while l < r :
    14. mid = l + r >> 1
    15. if dmap[w[i]][mid] > idx:
    16. r = mid
    17. else:
    18. l = mid + 1
    19. if r < 0 or dmap[w[i]][r] <= idx:
    20. ok = False
    21. break
    22. else:
    23. idx = dmap[w[i]][r]
    24. ans += 1 if ok else 0
    25. return ans
    26. 复制代码
    • 时间复杂度:令 n 为 s 长度,m 为 words 长度,l = 50 为 words[i]words[i] 长度的最大值。构造 map 的复杂度为 O(n)O(n);统计符合要求的 words[i]words[i] 的数量复杂度为 O(m \times l \times \log{n})O(m×l×logn)。整体复杂度为 O(n + m \times l \times \log{n})O(n+m×l×logn)
    • 空间复杂度:O(n)O(n)

    最后

    这是我们「刷穿 LeetCode」系列文章的第 No.792 篇,系列开始于 2021/01/01,截止于起始日 LeetCode 上共有 1916 道题目,部分是有锁题,我们将先把所有不带锁的题目刷完。

    在这个系列文章里面,除了讲解解题思路以外,还会尽可能给出最为简洁的代码。如果涉及通解还会相应的代码模板。

  • 相关阅读:
    CMU 15-445 Project 0 实现字典树
    吃透Chisel语言.35.Chisel进阶之硬件生成器(四)——利用函数式编程特性
    【软件安装】ubuntu+CGAL+QT可视化+draw_triangulation_2+draw_triangulation_3
    【Rust日报】2023-09-15 RustRover:JetBrains单行版Rust IDE
    拼多多item_get_app - 根据ID取商品详情原数据
    Go的接口,闭包,异常捕获
    【机器学习项目实战10例】(四):利用XGBoost实现短期电力负荷预测
    Open3D(C++) SVD分解求两个点云的变换矩阵
    高效阅读JDK源码,保姆级JDK源码笔记真香
    浏览器的进程和线程
  • 原文地址:https://blog.csdn.net/BASK2311/article/details/127915752