# 1055. Shortest Way to Form String

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) {
int res = 0, j = 0, m = source.size(), n = target.size();
while (j < n) {
int pre = j;
for (int i = 0; i < m; ++i) {
if (j < n && source[i] == target[j]) ++j;
}
if (j == pre) return -1;
++res;
}
return res;
}
};
``````

``````class Solution {
public:
int shortestWay(string source, string target) {
int res = 1, pos = -1, n = target.size();
for (int i = 0; i < n; ++i) {
if (source.find(target[i]) == -1) return -1;
pos = source.find(target[i], pos + 1);
if (pos == -1) {
++res;
pos = source.find(target[i]);
}
}
return res;
}
};
``````

Github 同步地址:

https://github.com/grandyang/leetcode/issues/1055

Is Subsequence

Number of Matching Subsequences

https://leetcode.com/problems/shortest-way-to-form-string/

https://leetcode.com/problems/shortest-way-to-form-string/discuss/350190/C%2B%2B-solution-faster-than-78.72-of-c%2B%2B-submission

https://leetcode.com/problems/shortest-way-to-form-string/discuss/330938/Accept-is-not-enough-to-get-a-hire.-Interviewee-4-follow-up

LeetCode All in One 题目讲解汇总(持续更新中…)

 微信打赏 Venmo 打赏
（欢迎加入博主的知识星球，博主将及时答疑解惑，并分享刷题经验与总结，试运营期间前五十位可享受半价优惠～）

×

Help us with donation