1055. Shortest Way to Form String
Input: source = "abc", target = "abcbc"
Output: 2
Explanation: The target "abcbc" can be formed by "abc" and "bc", which are subsequences of source "abc".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.Input: source = "xyz", target = "xzyxz"
Output: 3
Explanation: The target string can be constructed as follows "xz" + "y" + "xz".// Greedy Method
int shortestWay(string source, string target) { // time: O(n * m); space: O(1)
vector<bool> record(26, false);
int m = source.length(), n = target.length();
for (int i = 0; i < m; ++i) record[source[i] - 'a'] = true;
int res = 1, j = 0; // i: position in target string; j: position in source string
for (int i = 0; i < n; ++i) {
if (!record[target[i] - 'a']) return -1;
while (j < m && source[j] != target[i]) ++j;
// if j points to m, it means no match
if (j == m) {
j = -1;
++res;
--i;
}
++j;
}
return res;
}Last updated