zoukankan      html  css  js  c++  java
  • 792. Number of Matching Subsequences

    Given string S and a dictionary of words words, find the number of words[i] that is a subsequence of S.

    Example :
    Input: 
    S = "abcde"
    words = ["a", "bb", "acd", "ace"]
    Output: 3
    Explanation: There are three words in words that are a subsequence of S: "a", "acd", "ace".

    Note:

    • All words in words and S will only consists of lowercase letters.
    • The length of S will be in the range of [1, 50000].
    • The length of words will be in the range of [1, 5000].
    • The length of words[i] will be in the range of [1, 50].

    Approach #1: Array. [C++]

    class Solution {
    public:
        int numMatchingSubseq(string S, vector<string>& words) {
            vector<const char*> waiting[128];
            for (auto &w : words)
                waiting[w[0]].push_back(w.c_str());
            for (char c : S) {
                auto advance = waiting[c];
                waiting[c].clear();
                for (auto it : advance)
                    waiting[*++it].push_back(it);
            }
            return waiting[0].size();
        }
    };
    

      

    Approach #2: [Java]

    class Solution {
        public int numMatchingSubseq(String S, String[] words) {
            List<Integer[]>[] waiting = new List[128];
            for (int c = 0; c <= 'z'; ++c)
                waiting[c] = new ArrayList();
            for (int i = 0; i < words.length; ++i) 
                waiting[words[i].charAt(0)].add(new Integer[]{i, 1});
            for (char c : S.toCharArray()) {
                List<Integer[]> advance = new ArrayList(waiting[c]);
                waiting[c].clear();
                for (Integer[] a : advance)
                    waiting[a[1] < words[a[0]].length() ? words[a[0]].charAt(a[1]++) : 0].add(a);
            }
            return waiting[0].size();
        }
    }
    

      

    Reference:

    https://leetcode.com/problems/number-of-matching-subsequences/discuss/117634/Efficient-and-simple-go-through-words-in-parallel-with-explanation

    永远渴望,大智若愚(stay hungry, stay foolish)
  • 相关阅读:
    Scikit-learn学习记录【持续更新】——Scikit-learn框架的入门介绍
    【步骤超详细】mac系统 通过anaconda配置Pycharm的scikit-learn环境
    与高哥聊天有感
    蓝杰学长学姐交流记录
    Robcup2D足球学习记录【2020.01.06】
    分治算法
    多所学校就业报告分析总结
    想要半年之内拿到30万大厂的offer?看这里!!!
    C语言变量的存储类别
    C语言函数入门
  • 原文地址:https://www.cnblogs.com/h-hkai/p/10662914.html
Copyright © 2011-2022 走看看