题目描述:
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
andtarget
strings consist of only lowercase English letters from "a"-"z". - The lengths of
source
andtarget
string are between1
and1000
.
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;
}
};