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".
1 // first opinion is that we can use two pointer , one iterate src, another iterate tar. 2 // for each tar char, we move j until src[j] == tar[i], if j == src.length, res++, j = 0; 3 // in this solution, we greedy match as many chars from src to tar as possible which can lead mininum use of src. 4 // and we can build a set to save all the char in src, if there exists a char from tar which not exists in set, return -1. 5 public class Solution { 6 public int shortestWay(String source, String target) { 7 Set<Character> set = new HashSet<>(); 8 for (int i = 0; i < source.length(); i++) { 9 set.add(source.charAt(i)); 10 } 11 int indexSource = 0, indexTarget = 0, res = 0; 12 while (indexTarget < target.length()) { 13 if (!set.contains(target.charAt(indexTarget))) { 14 return -1; 15 } 16 while (indexSource < source.length() && source.charAt(indexSource) != target.charAt(indexTarget)) { 17 indexSource++; 18 } 19 if (indexSource == source.length()) { 20 res++; 21 indexSource = 0; 22 continue; 23 } 24 indexSource++; 25 indexTarget++; 26 } 27 return res + 1; 28 } 29 }
1 // follow up 1: yes, correct. could u implement it with O 1 space, which mean without set. 2 // okay. without set, we need a way to make sure there is a char which not in src. we can iterate src completely. if the j not move, then we can return -1. 3 4 public int shortestWay(String source, String target) { 5 int res = 0, i = 0; 6 while (i < target.length()) { 7 int originalI = i; 8 for (int j = 0; j < source.length(); j++) { 9 if (i < target.length() && target.charAt(i) == source.charAt(j)) { 10 i++; 11 } 12 } 13 if (i == originalI) return -1; 14 res++; 15 } 16 return res; 17 }

浙公网安备 33010602011771号