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)
  • 相关阅读:
    js设计模式之 适配器模式与应用场景
    2017版本的IDEA
    JAVA实验六——图形用户界面设计——6-47选择整数计算
    升级apache版本
    基于 PVE + TrueNAS 的私有云配置流程
    基于Win10+VS2019的ceres-solver-2.0.0配置流程
    基于PVE+ROS+LEDE的软路由配置流程
    启动android studio
    vscode配置
    找不到https://raw.githubusercontent.com
  • 原文地址:https://www.cnblogs.com/h-hkai/p/10662914.html
Copyright © 2011-2022 走看看