代码
双指针
class Solution {
public:
int shortestWay(string source, string target) {
int sp = 0, tp = 0, ans = 1;
int sn = source.size(), tn = target.size();
while(tp < tn){
while(sp < sn && source[sp] != target[tp]) ++sp;
if(sp == sn) {
sp = 0;
++ans;
while(sp < sn && source[sp] != target[tp]) ++sp;
if(sp == sn) return -1;
}
++sp, ++tp;
}
return ans;
}
};
优化双指针
class Solution {
public:
int shortestWay(string source, string target) {
vector<int> cnt[26];
int idx[26]{}, sp = 0, ans = 1;
const int sn = source.size(), tn = target.size();
for(int i = 0; i < sn; ++i){
cnt[source[i]-'a'].push_back(i);
}
for(int c: target){
c -= 'a';
auto&& p = cnt[c];
if(p.size() == 0) return -1;
while(idx[c] < p.size() && p[idx[c]] < sp) ++idx[c];
if(idx[c] == p.size()){
memset(idx, 0, sizeof(idx));
sp = 0;
++ans;
while(idx[c] < p.size() && p[idx[c]] < sp) ++idx[c];
}
sp = p[idx[c]] + 1;
}
return ans;
}
};
作者:MuriyaTensei
链接:https:
来源:力扣(LeetCode)
著作权归作者所有。商业转载请联系作者获得授权,非商业转载请注明出处。