1143. Longest Common Subsequence
class Solution:
def longestCommonSubsequence(self, a: str, b: str) -> int:
# if a[i] == b[j]: dp[i][j] = dp[i-1][j-1] + 1
# if a[i] != b[j]: dp[i][j] = max(dp[i-1][j], dp[i][j-1])
# dp[i][j] i, j is the number of chars in each string
n, m = len(a), len(b)
dp = [[0 for _ in range(m+1)] for _ in range(n+1)]
# i or j is 0, means one of the string size is 0, the common is 0
for i in range(1, n+1):
for j in range(1, m+1):
if a[i-1] == b[j-1]:
dp[i][j] = dp[i-1][j-1] + 1
else:
dp[i][j] = max(dp[i-1][j], dp[i][j-1])
return dp[-1][-1]
1548. The Most Similar Path in a Graph
class Solution:
def mostSimilar(self, n: int, roads: List[List[int]], names: List[str], tp: List[str]) -> List[int]:
# 思路和2个字符串找最长重复的子串思路一样 用二维dp
'''
Let's first calculate the minimum edit distance without worrying about the path. We can use 2D DP to do that:
dp[i][v] means the minimum edit distance for tp[:i+1] ending with city v.
The trainsition function is:
dp[i][v] = min(dp[i-1][u] + edit_cost(v)) for all edges (u, v)
, where edit_cost(v) at index i is names[v] != tp[i].
And