LeetCode #1055. Shortest Way to Form String

本文探讨了一种算法,旨在解决从源字符串中找到最小子序列组合,使其连接后等于目标字符串的问题。通过实例展示了算法的工作原理,如abc到abcbc的转换,以及遇到无法构造目标字符串的情况。算法利用了字符位置映射和上界查找来高效解决问题。

题目描述:

From any string, we can form a subsequence of that string by deleting some number of characters (possibly no deletions).

Given two strings source and target, return the minimum number of subsequences of source such that their concatenation equals target. If the task is impossible, return -1.

Example 1:

Input: source = "abc", target = "abcbc"
Output: 2
Explanation: The target "abcbc" can be formed by "abc" and "bc", which are subsequences of source "abc".

Example 2:

Input: source = "abc", target = "acdbc"
Output: -1
Explanation: The target string cannot be constructed from the subsequences of source string due to the character "d" in target string.

Example 3:

Input: source = "xyz", target = "xzyxz"
Output: 3
Explanation: The target string can be constructed as follows "xz" + "y" + "xz".

Constraints:

  • Both the source and target strings consist of only lowercase English letters from "a"-"z".
  • The lengths of source and target string are between 1 and 1000.
class Solution {
public:
    int shortestWay(string source, string target) {
        vector<vector<int>> pos(26);
        for(int i=0;i<source.size();i++) 
            pos[source[i]-'a'].push_back(i);
        int i=-1; // 必须让i初始化为-1,从而可以用upper_bound匹配到0
        int j=0;
        int count=0;
        while(j<target.size())
        {
            vector<int>& v=pos[target[j]-'a'];
            if(v.size()==0) return -1; // 说明source中没有target[j]字符
            auto it=upper_bound(v.begin(),v.end(),i);
            if(it==v.end())
            {
                i=-1;
                count++;
            }
            else
            {
                i=*it; // 迭代器的值就是source中匹配字符的下标
                j++;
            }
        }
        count++; // 最后一次没有匹配完source,但是还是要计数
        return count;
    }
};

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值