Saturday, August 17, 2019

Leetcode 392: Is Subsequence

https://leetcode.com/problems/is-subsequence/description/


Notes:

This question is an easy question. Using the so-called two-pointer method. The key is the follow-up question.

See the code below:

  1. class Solution {
  2. public:
  3.     bool isSubsequence(string s, string t) {
  4.         int i = 0, j = 0;
  5.         for(; j<t.size(); ++j) {
  6.             if(s[i] == t[j]) ++i;
  7.             if(i == s.size()) return true;
  8.         }
  9.         return i == s.size();
  10.     }
  11. };

Now let's look at the follow-up: now there are Billions of s. So we need to find a faster way than the above. One method is group and then binary search: group the index of the same kind of letter in t from small to high; then do a binary search to each letter in s. Or pre-processing t + binary search of s in t

See the code below:

  1. class Solution {
  2. public:
  3.     bool isSubsequence(string s, string t) {
  4.         vector<vector<int>> ids(26);//in the design, we can set ids as a private attribute
  5.                                     //and can be initialized when instantiating one object
  6.                                     //then call the
  7.         for(int i=0; i<t.size(); ++i) {
  8.             ids[t[i]-'a'].push_back(i);
  9.         }
  10.         int idx = -1;
  11.         for(int i=0; i<s.size(); ++i) {
  12.             int j = s[i] - 'a';
  13.             auto it = upper_bound(ids[j].begin(), ids[j].end(), idx);//the first bigger than idx
  14.             if(it == ids[j].end()) return false;
  15.             idx = *it;
  16.         }
  17.         return true;
  18.     }
  19. };

No comments:

Post a Comment