Shortest Way to Form String
From any string, we can form asubsequenceof that string by deleting some number of characters (possibly no deletions).
Given two stringssource
andtarget
, return the minimum number of subsequences ofsource
such that their concatenation equalstarget
. If the task is impossible, return-1
.
Example 1:
Example 2:
Example 3:
Note:
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
.
分析
贪心算法
每次遍历完整个source,target有 == 的就移动。下次继续继续重新遍历source。 返回遍历完多少次source
建inverted index:
这里i 其实可以当做source无限连接,i在source的Pos.在reverted Index list范围内就可以跳动,说明还在当前s内,范围外就重来再新一个s继续loop
Last updated
Was this helpful?