{"id":1936,"date":"2018-03-03T22:12:42","date_gmt":"2018-03-04T06:12:42","guid":{"rendered":"http:\/\/zxi.mytechroad.com\/blog\/?p=1936"},"modified":"2018-03-04T10:41:15","modified_gmt":"2018-03-04T18:41:15","slug":"leetcode-792-number-of-matching-subsequences","status":"publish","type":"post","link":"https:\/\/zxi.mytechroad.com\/blog\/string\/leetcode-792-number-of-matching-subsequences\/","title":{"rendered":"\u82b1\u82b1\u9171 LeetCode 792. Number of Matching Subsequences"},"content":{"rendered":"<p><iframe loading=\"lazy\" title=\"\u82b1\u82b1\u9171 LeetCode 792. Number of Matching Subsequences  - \u5237\u9898\u627e\u5de5\u4f5c EP172\" width=\"500\" height=\"375\" src=\"https:\/\/www.youtube.com\/embed\/l8_vcmjQA4g?feature=oembed\" frameborder=\"0\" allow=\"accelerometer; autoplay; clipboard-write; encrypted-media; gyroscope; picture-in-picture; web-share\" referrerpolicy=\"strict-origin-when-cross-origin\" allowfullscreen><\/iframe><\/p>\n<p>\u9898\u76ee\u5927\u610f\uff1a\u7ed9\u4f60\u4e00\u4e9b\u5355\u8bcd\uff0c\u95ee\u6709\u591a\u5c11\u5355\u8bcd\u51fa\u73b0\u5728\u5b57\u7b26\u4e32S\u7684\u5b50\u5e8f\u5217\u4e2d\u3002<\/p>\n<p><a href=\"https:\/\/leetcode.com\/problems\/number-of-matching-subsequences\/description\/\">https:\/\/leetcode.com\/problems\/number-of-matching-subsequences\/description\/<\/a><\/p>\n<p>Given string\u00a0<code>S<\/code>\u00a0and a\u00a0dictionary of words\u00a0<code>words<\/code>, find the number of\u00a0<code>words[i]<\/code>\u00a0that is a subsequence of\u00a0<code>S<\/code>.<\/p>\n<pre class=\"\">Example :\r\nInput: \r\nS = \"abcde\"\r\nwords = [\"a\", \"bb\", \"acd\", \"ace\"]\r\nOutput: 3\r\nExplanation: There are three words in <code>words<\/code> that are a subsequence of <code>S<\/code>: \"a\", \"acd\", \"ace\".<\/pre>\n<p><strong>Note:<\/strong><\/p>\n<ul>\n<li>All words in\u00a0<code>words<\/code>\u00a0and\u00a0<code>S<\/code>\u00a0will only consists of lowercase letters.<\/li>\n<li>The length of\u00a0<code>S<\/code>\u00a0will be in the range of\u00a0<code>[1, 50000]<\/code>.<\/li>\n<li>The length of\u00a0<code>words<\/code>\u00a0will be in the range of\u00a0<code>[1, 5000]<\/code>.<\/li>\n<li>The length of\u00a0<code>words[i]<\/code>\u00a0will be in the range of\u00a0<code>[1, 50]<\/code>.<\/li>\n<\/ul>\n<p><img loading=\"lazy\" decoding=\"async\" class=\"alignnone size-full wp-image-1956\" src=\"http:\/\/zxi.mytechroad.com\/blog\/wp-content\/uploads\/2018\/03\/792-ep172-1.png\" alt=\"\" width=\"960\" height=\"540\" srcset=\"https:\/\/zxi.mytechroad.com\/blog\/wp-content\/uploads\/2018\/03\/792-ep172-1.png 960w, https:\/\/zxi.mytechroad.com\/blog\/wp-content\/uploads\/2018\/03\/792-ep172-1-300x169.png 300w, https:\/\/zxi.mytechroad.com\/blog\/wp-content\/uploads\/2018\/03\/792-ep172-1-768x432.png 768w\" sizes=\"auto, (max-width: 960px) 100vw, 960px\" \/><\/p>\n<p><img loading=\"lazy\" decoding=\"async\" class=\"alignnone size-full wp-image-1955\" src=\"http:\/\/zxi.mytechroad.com\/blog\/wp-content\/uploads\/2018\/03\/792-ep172-2.png\" alt=\"\" width=\"960\" height=\"540\" srcset=\"https:\/\/zxi.mytechroad.com\/blog\/wp-content\/uploads\/2018\/03\/792-ep172-2.png 960w, https:\/\/zxi.mytechroad.com\/blog\/wp-content\/uploads\/2018\/03\/792-ep172-2-300x169.png 300w, https:\/\/zxi.mytechroad.com\/blog\/wp-content\/uploads\/2018\/03\/792-ep172-2-768x432.png 768w\" sizes=\"auto, (max-width: 960px) 100vw, 960px\" \/><\/p>\n<p><strong>Solution 1: Brute Force<\/strong><\/p>\n<p>Time complexity: O((S + L) * W)<\/p>\n<p>C++ w\/o cache TLE<\/p>\n<p>Space complexity: O(1)<\/p>\n<p>C++ w\/ cache 155 ms<\/p>\n<p>Space complexity: O(W * L)<\/p>\n<pre class=\"lang:default decode:true \">\/\/ Author: Huahua\r\n\/\/ Running time: 155 ms\r\nclass Solution {\r\npublic:\r\n  int numMatchingSubseq(const string&amp; S, vector&lt;string&gt;&amp; words) {    \r\n    int ans = 0;\r\n    unordered_map&lt;string, bool&gt; m;\r\n    for (const string&amp; word : words) {\r\n      auto it = m.find(word);\r\n      if (it == m.end()) {\r\n        bool match = isMatch(word, S);\r\n        ans += m[word] = match;\r\n      } else {\r\n        ans += it-&gt;second;\r\n      }\r\n    }\r\n    return ans;\r\n  }\r\n  \r\nprivate:\r\n  bool isMatch(const string&amp; word, const string&amp; S) {    \r\n    int start = 0;\r\n    for (const char c : word) {\r\n      bool found = false;\r\n      for (int i = start; i &lt; S.length(); ++i)\r\n        if (S[i] == c) {\r\n          found = true;\r\n          start = i + 1;          \r\n          break;\r\n        }\r\n      if (!found) return false;\r\n    }\r\n    return true;\r\n  }\r\n};<\/pre>\n<p><strong>Solution 2: Indexing+ Binary Search<\/strong><\/p>\n<p>Time complexity: O(S + W * L * log(S))<\/p>\n<p>Space complexity: O(S)<\/p>\n<p>S: length of S<\/p>\n<p>W: number of words<\/p>\n<p>L: length of a word<\/p>\n<p>C++<\/p>\n<pre class=\"lang:c++ decode:true \">\/\/ Author: Huahua\r\n\/\/ Running time: 183 ms\r\nclass Solution {\r\npublic:\r\n  int numMatchingSubseq(const string&amp; S, vector&lt;string&gt;&amp; words) {\r\n    vector&lt;vector&lt;int&gt;&gt; pos(128);    \r\n    for (int i = 0; i &lt; S.length(); ++i)\r\n      pos[S[i]].push_back(i);\r\n    int ans = 0;\r\n    for (const string&amp; word : words)\r\n      ans += isMatch(word, pos);\r\n    return ans;\r\n  }\r\n  \r\nprivate:\r\n  unordered_map&lt;string, bool&gt; m_;\r\n  bool isMatch(const string&amp; word, const vector&lt;vector&lt;int&gt;&gt;&amp; pos) {\r\n    if (m_.count(word)) return m_[word];       \r\n    int last_index = -1;\r\n    for (const char c : word) {\r\n      const vector&lt;int&gt;&amp; p = pos[c];\r\n      const auto it = std::lower_bound(p.begin(), p.end(), last_index + 1);      \r\n      if (it == p.end()) return m_[word] = false;\r\n      last_index = *it;      \r\n    }\r\n    return m_[word] = true;\r\n  }\r\n};<\/pre>\n<p>Java<\/p>\n<pre class=\"lang:java decode:true \">\/\/ Author: Huahua\r\n\/\/ Running time: 135 ms\r\nclass Solution {\r\n  private List&lt;List&lt;Integer&gt;&gt; pos;\r\n  private boolean isMatch(String word) {\r\n    int l = -1;\r\n    for (char c : word.toCharArray()) {\r\n      List&lt;Integer&gt; p = pos.get(c);\r\n      int index = Collections.binarySearch(p, l + 1);\r\n      if (index &lt; 0) index = -index - 1;\r\n      if (index &gt;= p.size()) return false;\r\n      l = p.get(index);\r\n    }\r\n    return true;\r\n  }\r\n  \r\n  public int numMatchingSubseq(String S, String[] words) {\r\n    pos = new ArrayList&lt;&gt;();\r\n    for (int i = 0; i &lt; 128; ++i) \r\n      pos.add(new ArrayList&lt;Integer&gt;());\r\n    char[] s = S.toCharArray();\r\n    for (int i = 0; i &lt; s.length; ++i)\r\n      pos.get(s[i]).add(i);\r\n    int ans = 0;\r\n    for (String word : words)\r\n      if (isMatch(word)) ++ans;\r\n    return ans;\r\n  }\r\n}<\/pre>\n<p>&nbsp;<\/p>\n<p>Python 3:<\/p>\n<p>w\/o cache<\/p>\n<pre class=\"lang:python decode:true \">\"\"\"\r\nAuthor: Huahua\r\nRunning time: 1120 ms\r\n\"\"\"\r\nclass Solution:\r\n  def numMatchingSubseq(self, S, words):\r\n    import bisect\r\n    def isMatch(word):      \r\n      l = -1\r\n      for c in word:\r\n        index = bisect.bisect_left(pos[c], l + 1)\r\n        if index == len(pos[c]): return 0\r\n        l = pos[c][index]          \r\n      return 1\r\n      \r\n    pos = {chr(i + ord('a')) : [] for i in range(26)}\r\n    for i, c in enumerate(S):\r\n      pos[c].append(i)\r\n    \r\n    return sum(map(isMatch, words))<\/pre>\n<p>w\/ cache<\/p>\n<pre class=\"lang:python decode:true \">\"\"\"\r\nAuthor: Huahua\r\nRunning time: 632 ms\r\n\"\"\"\r\nclass Solution:\r\n  def numMatchingSubseq(self, S, words):\r\n    import bisect\r\n    def isMatch(word):\r\n      if word in m: return m[word]\r\n      l = -1\r\n      for c in word:\r\n        index = bisect.bisect_left(pos[c], l + 1)\r\n        if index == len(pos[c]): \r\n          m[word] = 0\r\n          return 0\r\n        l = pos[c][index]\r\n      \r\n      m[word] = 1\r\n      return 1\r\n    \r\n    m = {}\r\n    pos = {chr(i + ord('a')) : [] for i in range(26)}\r\n    for i, c in enumerate(S):\r\n      pos[c].append(i)\r\n    \r\n    return sum(map(isMatch, words))<\/pre>\n<p>&nbsp;<\/p>\n","protected":false},"excerpt":{"rendered":"<p>\u9898\u76ee\u5927\u610f\uff1a\u7ed9\u4f60\u4e00\u4e9b\u5355\u8bcd\uff0c\u95ee\u6709\u591a\u5c11\u5355\u8bcd\u51fa\u73b0\u5728\u5b57\u7b26\u4e32S\u7684\u5b50\u5e8f\u5217\u4e2d\u3002 https:\/\/leetcode.com\/problems\/number-of-matching-subsequences\/description\/ Given string\u00a0S\u00a0and a\u00a0dictionary of words\u00a0words, find the number of\u00a0words[i]\u00a0that is a subsequence of\u00a0S. Example : Input: S = &#8220;abcde&#8221; words = [&#8220;a&#8221;, &#8220;bb&#8221;,&#8230;<\/p>\n","protected":false},"author":1,"featured_media":0,"comment_status":"open","ping_status":"open","sticky":false,"template":"","format":"standard","meta":{"footnotes":""},"categories":[149,47],"tags":[177,229],"class_list":["post-1936","post","type-post","status-publish","format-standard","hentry","category-binary-search","category-string","tag-medium","tag-subsequence","entry","simple"],"_links":{"self":[{"href":"https:\/\/zxi.mytechroad.com\/blog\/wp-json\/wp\/v2\/posts\/1936","targetHints":{"allow":["GET"]}}],"collection":[{"href":"https:\/\/zxi.mytechroad.com\/blog\/wp-json\/wp\/v2\/posts"}],"about":[{"href":"https:\/\/zxi.mytechroad.com\/blog\/wp-json\/wp\/v2\/types\/post"}],"author":[{"embeddable":true,"href":"https:\/\/zxi.mytechroad.com\/blog\/wp-json\/wp\/v2\/users\/1"}],"replies":[{"embeddable":true,"href":"https:\/\/zxi.mytechroad.com\/blog\/wp-json\/wp\/v2\/comments?post=1936"}],"version-history":[{"count":16,"href":"https:\/\/zxi.mytechroad.com\/blog\/wp-json\/wp\/v2\/posts\/1936\/revisions"}],"predecessor-version":[{"id":1958,"href":"https:\/\/zxi.mytechroad.com\/blog\/wp-json\/wp\/v2\/posts\/1936\/revisions\/1958"}],"wp:attachment":[{"href":"https:\/\/zxi.mytechroad.com\/blog\/wp-json\/wp\/v2\/media?parent=1936"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/zxi.mytechroad.com\/blog\/wp-json\/wp\/v2\/categories?post=1936"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/zxi.mytechroad.com\/blog\/wp-json\/wp\/v2\/tags?post=1936"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}