Saturday, August 17, 2019

Leetcode 792: Number of Matching Subsequences

https://leetcode.com/problems/number-of-matching-subsequences/description/


Notes:

This question is the same as the follow up question of Leetcode 392.

See the code below:

  1. class Solution {
  2. public:
  3.     int numMatchingSubseq(string S, vector<string>& words) {
  4.         int res = 0;
  5.         vector<vector<int>> ids(26);
  6.         for(int i=0; i<S.size(); ++i) ids[S[i]-'a'].push_back(i);
  7.         for(auto &w : words) {
  8.             if(w.size() > S.size()) continue;
  9.             int id = -1, i = 0;
  10.             for(; i<w.size(); ++i) {
  11.                 int t = w[i] - 'a';
  12.                 auto it = upper_bound(ids[t].begin(), ids[t].end(), id);
  13.                 if(it == ids[t].end()) break;
  14.                 id = *it;
  15.             }
  16.             if(i == w.size()) ++res;
  17.         }
  18.         return res;
  19.     }
  20. };

No comments:

Post a Comment