题目:原题链接(中等)
标签:贪心算法、动态规划、二分查找
解法 | 时间复杂度 | 空间复杂度 | 执行用时 |
---|---|---|---|
Ans 1 (Python) | O ( S + T L o g S ) O(S+TLogS) O(S+TLogS) | O ( S ) O(S) O(S) | 44ms (88.14%) |
Ans 2 (Python) | |||
Ans 3 (Python) |
解法一:
class Solution:
def shortestWay(self, source: str, target: str) -> int:
alphabets = set(source)
for ch in target:
if ch not in alphabets:
return -1
index = collections.defaultdict(list)
for i, ch in enumerate(source):
index[ch].append(i)
ans = 1
i = -1
for ch in target:
j = bisect.bisect_right(index[ch], i)
if j == len(index[ch]):
j = 0
ans += 1
i = index[ch][j]
return ans