Leetcode1055. 形成字符串的最短路径 动态规划.线性动态规划.单串问题 双指针

代码

双指针

class Solution {
public:
    int shortestWay(string source, string target) {
        int sp = 0, tp = 0, ans = 1;
        //两个指针
        int sn = source.size(), tn = target.size();
        //两个max
        while(tp < tn){
            //对比sp指向的值和tp指向的值
            while(sp < sn && source[sp] != target[tp]) ++sp;//找到遍历source找到和当前target一样的一位.
            if(sp == sn) {
                //如果找完了source且没找到,要么是这个source和target的一次子串匹配结束,要么是一个没有成功。
                //从头再比一次
                sp = 0;
                ++ans;
                while(sp < sn && source[sp] != target[tp]) ++sp;//如果再次对比到结尾,则有无法匹配的,结束
                if(sp == sn) return -1;
            }
            //有相等且未到最后,则两个都增长一下。其实就是从下个sp位置开始找下个和tp相等的。
            ++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.cn/problems/shortest-way-to-form-string/solution/c-zhu-bu-you-hua-shuang-zhi-zhen-duo-zhi-1hvh/
来源:力扣(LeetCode)
著作权归作者所有。商业转载请联系作者获得授权,非商业转载请注明出处。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值