LeetCode 솔루션 분류

[6/14] 583. Delete Operation for Two Strings

컨텐츠 정보

본문

Medium
319749Add to ListShare

Given two strings word1 and word2, return the minimum number of steps required to make word1 and word2 the same.

In one step, you can delete exactly one character in either string.

 

Example 1:

Input: word1 = "sea", word2 = "eat"
Output: 2
Explanation: You need one step to make "sea" to "ea" and another step to make "eat" to "ea".

Example 2:

Input: word1 = "leetcode", word2 = "etco"
Output: 4

 

Constraints:

  • 1 <= word1.length, word2.length <= 500
  • word1 and word2 consist of only lowercase English letters.

관련자료

댓글 2

학부유학생님의 댓글

  • 익명
  • 작성일
Runtime: 392 ms, faster than 51.22% of Python3 online submissions for Delete Operation for Two Strings.
Memory Usage: 13.9 MB, less than 92.06% of Python3 online submissions for Delete Operation for Two Strings.
class Solution:
    def minDistance(self, word1: str, word2: str) -> int:
        if len(word1) < len(word2):
            word1, word2 = word2, word1
            
        long, short = len(word1), len(word2)
        
        prev = [i for i in range(long+1)]
        
        for idx, char in enumerate(word2):
            curr = [0]*(long+1)
            curr[0] = idx + 1
            for i in range(1,long+1):
                if char == word1[i-1]:
                    curr[i] = prev[i-1]
                else:
                    curr[i] = 1+min(prev[i], curr[i-1])
            
            prev = curr
        
        return curr[-1]

Coffee님의 댓글

  • 익명
  • 작성일
class Solution {
    public int minDistance(String word1, String word2) {
        int[][] dp = new int[word1.length() +1][word2.length()+1];
        
        for(int i=0; i<=word1.length(); i++){
            for(int j=0; j<=word2.length(); j++){
                if(i == 0 || j == 0){
                    continue;
                }
                
                if(word1.charAt(i-1) == word2.charAt(j-1)){
                    dp[i][j] = 1 + dp[i-1][j-1];
                }else{
                    dp[i][j] = Math.max(dp[i-1][j], dp[i][j-1]);
                }
            }
        }
        
        return word1.length() + word2.length() - 2 * dp[word1.length()][word2.length()];
    }
    
    
}
LeetCode 솔루션 357 / 12 페이지
번호
제목
이름

최근글


인기글


새댓글


Stats


  • 현재 접속자 957 명
  • 오늘 방문자 8,410 명
  • 어제 방문자 8,829 명
  • 최대 방문자 14,831 명
  • 전체 회원수 1,566 명
알림 0