1. 给定字符数组String和一个字符串s,给定一个开始查找的索引,计算组成字符串s的最短步数。
比如:
- 输入:String = 'aemoyn' , s = 'amo', index = 0
- 输出:3
- 分析:0+2+1=3
分析:
(1)法1:递归求解(贪婪算法)——比较暴力,时间复杂度高。
(2)法2:动态规划——速度更快!!时间复杂度低。分阶段求解。
def solve(string, s, index):
dict = {}
for i, x in enumerate(string):
if x in dict.keys():
dict[x].append(i)
else:
dict[x] = [i]
s_index = [dict[x] for x in s]
# return cal_step_greefy(index, s_index, len(string))
return cal_step_dynamic(index, s_index, len(string))
# 递归求解(贪婪算法)
def cal_step_greedy(index, s_index, string_L):
if len(s_index) == 1:
steps = [min(abs(index - p), string_L - abs(index - p)) for p in s_index[0]]
return min(steps)
steps = [min(abs(index - p), string_L - abs(index - p)) + cal_step_greedy(p, s_index[1:], string_L) for p in
s_index[0]]
return min(steps)
# 动态规划
def cal_step_dynamic(index, s_index, string_L):
dp = [x for x in s_index]
dp[0] = [min(abs(index - x), string_L - abs(index - x)) for x in dp[0]]
for i in range(1, len(s_index)):
dp[i] = [min([dp[i - 1][t[0]] + min(abs(t[1] - x), string_L - abs(t[1] - x)) for t in enumerate(s_index[i - 1])]) for x in dp[i]]
return min(dp[-1])
if __name__ == "__main__":
import sys
string = sys.stdin.readline().strip()
s = sys.stdin.readline().strip()
index = int(sys.stdin.readline().strip())
print(solve(string, s, index))