936、Stamping The Sequence戳印序列
难度:困难
题目描述
英文:
You want to form a
target
string of lowercase letters.At the beginning, your sequence is
target.length
'?'
marks. You also have astamp
of lowercase letters.On each turn, you may place the stamp over the sequence, and replace every letter in the sequence with the corresponding letter from the stamp. You can make up to
10 * target.length
turns.For example, if the initial sequence is “?????”, and your stamp is
"abc"
, then you may make “abc??”, “?abc?”, “??abc” in the first turn. (Note that the stamp must be fully contained in the boundaries of the sequence in order to stamp.)If the sequence is possible to stamp, then return an array of the index of the left-most letter being stamped at each turn. If the sequence is not possible to stamp, return an empty array.
For example, if the sequence is “ababc”, and the stamp is
"abc"
, then we could return the answer[0, 2]
, corresponding to the moves “?????” -> “abc??” -> “ababc”.Also, if the sequence is possible to stamp, it is guaranteed it is possible to stamp within
10 * target.length
moves. Any answers specifying more than this number of moves will not be accepted.中文:
你想要用小写字母组成一个目标字符串
target
。开始的时候,序列由
target.length
个'?'
记号组成。而你有一个小写字母印章stamp
。在每个回合,你可以将印章放在序列上,并将序列中的每个字母替换为印章上的相应字母。你最多可以进行
10 * target.length
个回合。举个例子,如果初始序列为 “?????”,而你的印章
stamp
是"abc"
,那么在第一回合,你可以得到 “abc??”、”?abc?”、”??abc”。(请注意,印章必须完全包含在序列的边界内才能盖下去。)如果可以印出序列,那么返回一个数组,该数组由每个回合中被印下的最左边字母的索引组成。如果不能印出序列,就返回一个空数组。
例如,如果序列是 “ababc”,印章是
"abc"
,那么我们就可以返回与操作 “?????” -> “abc??” -> “ababc” 相对应的答案[0, 2]
;另外,如果可以印出序列,那么需要保证可以在
10 * target.length
个回合内完成。任何超过此数字的答案将不被接受。
提示
1 <= stamp.length <= target.length <= 1000
stamp
和target
只包含小写字母。
示例
Example 1:
1 | Input: stamp = "abc", target = "ababc" |
Example 2:
1 | Input: stamp = "abca", target = "aabcaca" |
解题思路
思路一
题目是从?????
到ababc
的问题,替换时要考虑会覆盖到已经替换好的部分。可以逆向替换,从ababc
到?????
,?
可以看做通配符,遍历target
,逐位和stamp
比较,如果可以匹配到,则记录当时的index
,并修改覆盖后的字符,循环上述过程,直到得到了?????
序列或无法继续匹配下去。
例如,stamp='abca'
,target='aabcaca'
,则整个替换过程为aabcaca => a????ca => ?????ca => ???????
,替换位置索引序列为1->0->3
,所以题目所求的序列即为[3,0,1]
。
代码提交
Python2,用时6480ms,内存10.9M
1 | class Solution(object): |
思路二
上述方法一的checkstamp
过程有很多重复计算,事实上不需要每次都从头开始遍历,可以进行一些优化。
只进行一次字符串匹配的循环,在时间进行了优化,相应的内存消耗增加。
记录每一个位置 i 对应长度为lenS的字符串上有哪些部分是能对应的,哪些些是不对应的。再将完全对应的字符串的位置全部压入队列。
在队列中的每一个位置都是已匹配位置,在change中声明当前位置已匹配,之后考虑当前位置改动后可能会产生影响的所有位置 i 对应的长度为lenS的字符串。
代码提交
Python2,用时436ms,内存14.4M
1 | import collections |