动态规划 | HJ52 计算字符串的编辑距离
while True: try: s1 = input() s2 = input() if len(s2) < len(s1): s1, s2 = s2, s1 cnt = 0 dp = [[-1]*(len(s2)+1) for _ in range(len(s1)+1)] for i in range(len(s1)+1): dp[i][0] = i for j in range(len(s2)+1): dp[0][j] = j for i in range(1, len(s1)+1): for j in range(1, len(s2)+1): if s1[i-1] == s2[j-1]: dp[i][j] = dp[i-1][j-1] else: # 分别代表s2添加(i-1后s1少1字符,s2相对多1字符)、删除、替换 last = min(dp[i-1][j], dp[i][j-1], dp[i-1][j-1]) dp[i][j] = 1 + last print(dp[-1][-1]) except: break
用时:2h
华为笔试刷题 文章被收录于专栏
高质量题: 1~40:HJ16,HJ22,HJ24,HJ26,HJ27,HJ28,HJ35,HJ37,HJ39; 40~80:HJ41,HJ42,HJ43,HJ44,HJ48,HJ50,HJ52,HJ53,HJ57,HJ61,HJ63,HJ64,HJ70,HJ71,HJ74,HJ77; 80~108:HJ82,HJ85,HJ88,HJ89,HJ93,HJ95,HJ98,HJ103,HJ107