0791-0800

791. Custom Sort String $\star\star$

792. Number of Matching Subsequences $\star\star$

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
class Solution {
 public:
  int numMatchingSubseq(string S, vector<string>& words) {
    for (const string& word : words) insert(word);

    return dfs(S, 0, &root);
  }

 private:
  struct TrieNode {
    TrieNode() : children(26), count(0) {}
    ~TrieNode() {
      for (TrieNode* child : children) delete child;
    }

    vector<TrieNode*> children;
    int count;
  };

  void insert(const string& word) {
    TrieNode* node = &root;
    for (char c : word) {
      TrieNode*& next = node->children[c - 'a'];
      if (!next) next = new TrieNode;
      node = next;
    }
    ++node->count;
  }

  int dfs(const string& S, int s, TrieNode* node) {
    int ans = node->count;

    if (s >= S.length()) return ans;

    for (int i = 0; i < 26; ++i)
      if (node->children[i]) {
        int index = indexOf(S, i + 'a', s);
        if (index != -1) ans += dfs(S, index + 1, node->children[i]);
      }

    return ans;
  }

  int indexOf(const string& S, char c, int s) {
    for (int i = s; i < S.length(); ++i)
      if (S[i] == c) return i;
    return -1;
  }

  TrieNode root;
};

793. Preimage Size of Factorial Zeroes Function $\star\star\star$

794. Valid Tic-Tac-Toe State $\star\star$

795. Number of Subarrays with Bounded Maximum $\star\star$

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
class Solution {
 public:
  int numSubarrayBoundedMax(vector<int>& A, int L, int R) {
    int ans = 0;
    int l = -1;
    int r = -1;

    for (int i = 0; i < A.size(); ++i) {
      if (A[i] > R) l = i;
      if (A[i] >= L) r = i;
      ans += r - l;
    }

    return ans;
  }
};

796. Rotate String $\star$

797. All Paths From Source to Target $\star\star$

798. Smallest Rotation with Highest Score $\star\star\star$

799. Champagne Tower $\star\star$

800. Similar RGB Color $\star$