标签:return String Form int cur source Way string target
原题链接在这里: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:
1 class Solution { 2 public int shortestWay(String source, String target) { 3 if(source == null || target == null){ 4 return -1; 5 } 6 7 if(target.length() == 0){ 8 return 0; 9 } 10 11 int res = 0; 12 int m = source.length(); 13 int n = target.length(); 14 int cur = 0; 15 while(cur < n){ 16 int temp = cur; 17 for(int i = 0; i < m && cur < n; i++){ 18 if(source.charAt(i) == target.charAt(cur)){ 19 cur++; 20 } 21 } 22 23 if(temp == cur){ 24 return -1; 25 } 26 27 res++; 28 } 29 30 return res; 31 } 32 }
标签:return,String,Form,int,cur,source,Way,string,target 来源: https://www.cnblogs.com/Dylan-Java-NYC/p/12204123.html
本站声明: 1. iCode9 技术分享网(下文简称本站)提供的所有内容,仅供技术学习、探讨和分享; 2. 关于本站的所有留言、评论、转载及引用,纯属内容发起人的个人观点,与本站观点和立场无关; 3. 关于本站的所有言论和文字,纯属内容发起人的个人观点,与本站观点和立场无关; 4. 本站文章均是网友提供,不完全保证技术分享内容的完整性、准确性、时效性、风险性和版权归属;如您发现该文章侵犯了您的权益,可联系我们第一时间进行删除; 5. 本站为非盈利性的个人网站,所有内容不会用来进行牟利,也不会利用任何形式的广告来间接获益,纯粹是为了广大技术爱好者提供技术内容和技术思想的分享性交流网站。