algorithm

72. Edit Distance

식피두 2020. 9. 12. 01:05

https://leetcode.com/problems/edit-distance/

 

Edit Distance - LeetCode

Level up your coding skills and quickly land a job. This is the best place to expand your knowledge and get prepared for your next interview.

leetcode.com

방향에 의미 부여하기

 

328 ms

class Solution:
    def minDistance(self, word1: str, word2: str) -> int:
        if len(word1) == 0 or len(word2) == 0:
            return max(len(word1), len(word2))
        
        dp = []
        for i in range(len(word1)+1):
            if i == 0:
                dp.append(list(range(len(word2)+1)))
                continue
            dp.append([i]+[float('inf')]*(len(word2)))
        
        for _i, a in enumerate(word1):
            i = _i+1
            for _j, b in enumerate(word2):
                j = _j+1
                dp[i][j] = min(dp[i][j], dp[i-1][j]+1)
                dp[i][j] = min(dp[i][j], dp[i][j-1]+1)
                if a == b:
                    dp[i][j] = min(dp[i][j], dp[i-1][j-1])
                else:
                    dp[i][j] = min(dp[i][j], dp[i-1][j-1]+1)
        
        return dp[len(word1)][len(word2)]

 

dp 2차원 배열을 선언하지 않고, queue를 이용해 특이하게 풀었다.

이해해보자.

 

52ms

class Solution:
  def minDistance(self, word1: str, word2: str) -> int:
      l1,l2 = len(word1),len(word2)
      visited = set()
      q = deque([(0, 0, 0)])
        
      while q:
        p1, p2, dist = q.popleft()
        if (p1, p2) not in visited and p1<=l1 and p2<=l2:
          visited.add((p1, p2))
          
          if word1[p1:] == word2[p2:]:
            return dist

          while p1<l1 and p2<l2 and word1[p1] == word2[p2]:
            p1 += 1
            p2 += 1

          dist += 1
          q.extend([(p1+1, p2+1, dist), (p1, p2+1, dist), (p1+1, p2, dist)])

'algorithm' 카테고리의 다른 글

1405. Longest Happy String  (0) 2020.09.14
638. Shopping Offers  (0) 2020.09.12
1143. Longest Common Subsequence  (0) 2020.09.10
674. Longest Continuous Increasing Subsequence  (0) 2020.09.07
1155. Number of Dice Rolls With Target Sum  (0) 2020.09.07