题目描述:
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
sourceandtargetstrings consist of only lowercase English letters from "a"-"z". - The lengths of
sourceandtargetstring are between1and1000.
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;
}
};
本文探讨了一种算法,旨在解决从源字符串中找到最小子序列组合,使其连接后等于目标字符串的问题。通过实例展示了算法的工作原理,如abc到abcbc的转换,以及遇到无法构造目标字符串的情况。算法利用了字符位置映射和上界查找来高效解决问题。
463

被折叠的 条评论
为什么被折叠?



