【leetcode】Edit Distance (hard)
3402 단어 LeetCode
You have the following 3 operations permitted on a word:
a) Insert a characterb) Delete a characterc) Replace a character
생각:
이것은 작년에 알고리즘을 배울 때 배웠는데, 당시에는 매우 어려웠는데, 지금 보니 이 문제는 정말 간단하다.바로 일반적인 동적 기획 제목이다.직접 AC, 기쁘다~~
dp[m][n]으로word1의 전 m자와word2의 전 n자의 최소 일치 거리를 저장합니다.
그러면 dp[i][j]= dp[i-1][j]+1(word1은 문자를 삭제), dp[i][j-1]+1(word2는 문자를 삭제), dp[i-1][j-1]+((word1[i-1]=word2[j-1])?0 (현재 문자 동일): 1 (대체) 에서 가장 작은 값입니다.
class Solution {
public:
int minDistance(string word1, string word2) {
int len1 = word1.length();
int len2 = word2.length();
vector<vector<int>> dp(len1 + 1, vector<int>(len2 + 1, 0));
for(int i = 1; i < len1 + 1; i++)
{
dp[i][0] = i;
}
for(int j = 1; j < len2 + 1; j++)
{
dp[0][j] = j;
}
for(int i = 1; i < len1 + 1; i++)
{
for(int j = 1;j < len2 + 1; j++)
{
dp[i][j] = min(min(dp[i-1][j] + 1, dp[i][j-1] + 1), dp[i-1][j-1] + ((word1[i-1]==word2[j-1]) ? 0 : 1));
}
}
return dp[len1][len2];
}
};