LeetCode 1055. Shortest Way to Form String
原题链接在这里:https://leetcode.com/problems/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
andtarget
strings consist of only lowercase English letters from "a"-"z". - The lengths of
source
andtarget
string are between1
and1000
.
题解:
Iterate through the source to move pointer in target as much as possible.
After one iteration, res++.
If we could come to the end of target, return res.
If go through one iteration, the pointer in target is not changed, then return -1.
Time Compleixty: O(n + res * m). n = target.length(). m = source.length().
Space: O(1).
AC Java:
class Solution { public int shortestWay(String source, String target) { if(source == null || target == null){ return -1; } if(target.length() == 0){ return 0; } int res = 0; int m = source.length(); int n = target.length(); int cur = 0; while(cur < n){ int temp = cur; for(int i = 0; i < m && cur < n; i++){ if(source.charAt(i) == target.charAt(cur)){ cur++; } } if(temp == cur){ return -1; } res++; } return res; } }