Longest Common Subsequence
class Solution:
"""
@param A: A string
@param B: A string
@return: The length of longest common subsequence of A and B
"""
def longestCommonSubsequence(self, A, B):
# write your code here
if not A or not B:
return 0
len1=len(A)
len2=len(B)
f=[[0]*(len2+1) for _ in range(len1+1)]
for i in range(1,len1+1):
for j in range(1,len2+1):
if A[i-1]==B[j-1]:
f[i][j]=f[i-1][j-1]+1
else:
f[i][j]=max(f[i-1][j],f[i][j-1])
return f[-1][-1]
Interleaving String
class Solution:
"""
@param s1: A string
@param s2: A string
@param s3: A string
@return: Determine whether s3 is formed by interleaving of s1 and s2
"""
def isInterleave(self, s1, s2, s3):
# write your code here
if not s1:
return s3==s2
if not s2:
return s3==s1
if len(s1)+len(s2)!=len(s3):
return False
len1=len(s1)
len2=len(s2)
f=[[False]*(len2+1) for i in range(len1+1)]
f[0][0]=True
for i in range(0,len1+1):
for j in range(0,len2+1):
k=i+j
if i>=1 and s3[k-1]==s1[i-1]:
f[i][j]=f[i-1][j]
if j>=1 and s3[k-1]==s2[j-1]:
f[i][j]=f[i][j] or f[i][j-1]
return f[-1][-1]
Edit distance
class Solution:
"""
@param word1: A string
@param word2: A string
@return: The minimum number of steps.
"""
def minDistance(self, word1, word2):
# write your code here
if not word1 and not word2:
return 0
if not word1:
return len(word2)
if not word2:
return len(word1)
len1=len(word1)
len2=len(word2)
f=[[float('inf')]*(len2+1) for i in range(len1+1)]
f[0][0]=0
for i in range(len1+1):
for j in range(len2+1):
if i==0:
f[i][j]=j
if j==0:
f[i][j]=i
if i>=1 and j>=1:
if word1[i-1]==word2[j-1]:
f[i][j]=f[i-1][j-1]
else:
f[i][j]=min(f[i][j-1]+1,f[i-1][j]+1,f[i-1][j-1]+1)
return f[-1][-1]
Distinct Subsequence
class Solution:
"""
@param: : A string
@param: : A string
@return: Count the number of distinct subsequences
"""
def numDistinct(self, S, T):
# write your code here
if not S:
return 0
if not T:
return 1
n1=len(S)
n2=len(T)
f=[[0]*(n2+1) for i in range(n1+1)]
for i in range(n1+1):
for j in range(n2+1):
if j==0:
f[i][j]=1
continue
if i==0:
f[i][j]=0
continue
f[i][j]=f[i-1][j]
if S[i-1]==T[j-1]:
f[i][j]=f[i][j]+f[i-1][j-1]
return f[-1][-1]
Regular Expression Matching