<p>Given a string <code>s</code> and an array of strings <code>words</code>, return <em>the number of</em> <code>words[i]</code> <em>that is a subsequence of</em> <code>s</code>.</p>

<p>A <strong>subsequence</strong> 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.</p>

<ul>
	<li>For example, <code>&quot;ace&quot;</code> is a subsequence of <code>&quot;abcde&quot;</code>.</li>
</ul>

<p>&nbsp;</p>
<p><strong class="example">Example 1:</strong></p>

<pre>
<strong>Input:</strong> s = &quot;abcde&quot;, words = [&quot;a&quot;,&quot;bb&quot;,&quot;acd&quot;,&quot;ace&quot;]
<strong>Output:</strong> 3
<strong>Explanation:</strong> There are three strings in words that are a subsequence of s: &quot;a&quot;, &quot;acd&quot;, &quot;ace&quot;.
</pre>

<p><strong class="example">Example 2:</strong></p>

<pre>
<strong>Input:</strong> s = &quot;dsahjpjauf&quot;, words = [&quot;ahjpjau&quot;,&quot;ja&quot;,&quot;ahbwzgqnuk&quot;,&quot;tnmlanowax&quot;]
<strong>Output:</strong> 2
</pre>

<p>&nbsp;</p>
<p><strong>Constraints:</strong></p>

<ul>
	<li><code>1 &lt;= s.length &lt;= 5 * 10<sup>4</sup></code></li>
	<li><code>1 &lt;= words.length &lt;= 5000</code></li>
	<li><code>1 &lt;= words[i].length &lt;= 50</code></li>
	<li><code>s</code> and <code>words[i]</code> consist of only lowercase English letters.</li>
</ul>

class Solution {
public:
  int numMatchingSubseq(string s, vector<string>& words) {
    //  序列自动机
    int n = s.size();
    vector<vector<int>> au(n + 1, vector<int>(26));
    s = "#" + s;
    for (int i = n - 1; i >= 0; i--)
      for (char ch = 'a'; ch <= 'z'; ch++) {
        int idx = ch - 'a';
        if (s[i + 1] == ch) au[i][idx] = i + 1;
        else au[i][idx] = au[i + 1][idx];
      }

    int res = 0;
    auto f = [&](string& s) {
      int idx = 0;
      for (char ch : s) {
        if (!au[idx][ch - 'a']) return false;
        idx = au[idx][ch - 'a'];
      }
      return true;
    };
    for (auto& w : words) {
      if (f(w)) res++;
    }
    return res;
  }
};
// Deterministic Finite Automata
// s = "abcde"
// t = "bbd"
// 序列自动机
// a[i][ch] = s中下标i后面第一次出现ch字符的位置
// a[i][ch] = s[i+1]==ch? i+1: a[i+1][ch]
// 给定任意一个字符串t，长度为m，可以在O(m)的时间内验证t是否是s的子序列

// 台词
// Let s = " " + s, in order to start the index from 1, for convenience reason. We define a 2d array, f[i][ch] meaning the first occurrence of ch in s substring starting from s[i]. 
// After constructing this data structure, we answer the query. If we want to query string t, traverse t, and starting from idx = 0, for each character ch, we check f[idx][ch], if it's 0, then not a subsequence; otherwise update idx to be f[idx][ch]. If t is completely traversed, then yes, it is a subsequence.



400830