Advertisement
nikunjsoni

1055

Jun 7th, 2021
97
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 0.99 KB | None | 0 0
  1. class Solution {
  2. public:
  3.     int shortestWay(string source, string target) {
  4.         int slen = source.length(), tlen = target.length();
  5.         int ans=0, i=0, pos=-1;
  6.         while(i<tlen && ans<=i){
  7.             pos = source.find(target[i], pos+1);
  8.             if(pos == string::npos){
  9.                 ans++;
  10.                 pos = source.find(target[i]);
  11.                 if(pos == string::npos) return -1;
  12.             }
  13.             i++;
  14.         }
  15.         return ans+1;
  16.     }
  17. };
  18.  
  19. ---------------------
  20.  
  21. class Solution {
  22. public:
  23.     int shortestWay(string s, string t, int res = 0) {
  24.       vector<int> ch_ids[26] = {};
  25.       for (auto j = 0; j < s.size(); ++j) ch_ids[s[j] - 'a'].push_back(j);
  26.       for (auto i = 0, j = -1; i < t.size(); ) {
  27.         auto &ids = ch_ids[t[i] - 'a'];
  28.         if (ids.empty()) return -1;
  29.         auto it = upper_bound(begin(ids), end(ids), j);
  30.         if(it == end(ids)) ++res, j = -1;
  31.         else ++i, j = *it;
  32.       }
  33.       return res + 1;
  34.     }
  35. };
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement