Delete Operation for Two Strings
LeetCode 583 · ಮಧ್ಯಮ · ಪರಿಹಾರ, intuition ಮತ್ತು ಹಂತ ಹಂತದ ವಾಕ್ಥ್ರೂ
deletions = (m − LCS) + (n − LCS).
ನಾನು Delete Operation for Two Strings (LeetCode 583) ಅನ್ನು ಹೀಗೆ ಪರಿಹರಿಸಿದೆ — LCS ಪ್ಯಾಟರ್ನ್ನ ಒಂದು ಮಧ್ಯಮ ಪ್ರಾಬ್ಲಮ್. ಕೆಳಗೆ: intuition, ಹಂತ ಹಂತದ approach, ನನ್ನ accepted Python ಕೋಡ್, animated test cases ಮತ್ತು line-by-line debugger.
ಕೆಳಗಿನ ವಿವರಣೆ ಇಂಗ್ಲಿಷ್ನಲ್ಲಿದೆ.
Intuition
Whatever you keep in both strings must be a common subsequence, and you want to keep as much as possible. So keep the longest common subsequence and delete everything else from each word.
Approach
- 1
Compute the LCS length with a bottom-up table.
- 2
Characters outside the LCS must be deleted from each word.
- 3
Return (m − lcs) + (n − lcs).
ನಾನು ಹೇಗೆ ಪರಿಹರಿಸಿದೆ
LCS reductionPythonO(m·n) time · O(m·n) space
class Solution:
def longestCommonSubsequence(self,text1: str, text2: str) -> int:
dp = [[0] * (len(text2) + 1) for _ in range(len(text1) + 1)]
for i in reversed(range((len(text1)))):
for j in reversed(range(len(text2))):
if text1[i] == text2[j]:
dp[i][j] = 1 + dp[i + 1][j + 1]
else:
dp[i][j] = max(dp[i + 1][j], dp[i][j + 1])
return dp[0][0]
def minDistance(self, word1: str, word2: str) -> int:
m=len(word1)
n =len(word2) #sea, eat, lcs ea - 2 (3-2) deletions + 3-2 deletions
x = self.longestCommonSubsequence(word1,word2)
return (m-x) + (n-x)Delete Operation for Two Strings — ಪದೇ ಪದೇ ಕೇಳುವ ಪ್ರಶ್ನೆಗಳು
Delete Operation for Two Strings ಹಿಂದಿನ intuition ಏನು?
Whatever you keep in both strings must be a common subsequence, and you want to keep as much as possible. So keep the longest common subsequence and delete everything else from each word.
Delete Operation for Two Strings (LeetCode 583) ಅನ್ನು ಹೇಗೆ ಪರಿಹರಿಸುವುದು?
1. Compute the LCS length with a bottom-up table. 2. Characters outside the LCS must be deleted from each word. 3. Return (m − lcs) + (n − lcs).
Delete Operation for Two Strings ನ time ಮತ್ತು space complexity ಎಷ್ಟು?
Time: O(m · n). Space: O(m · n). (Accepted approach: LCS reduction.)
Delete Operation for Two Strings ನಲ್ಲಿ ಸಾಮಾನ್ಯ ತಪ್ಪುಗಳು ಯಾವುವು?
Recognising the reduction to LCS is the whole problem.