LeetCode_Edit Distance
Given two words word1 and word2, find the minimum number of steps required to convert word1 to word2. (each operation is counted as 1 step.) You have the following 3 operations permitted on a word: a) Insert a character b) Delete a character c) Replace a character |
class Solution { public : int minDistance(string word1, string word2) { // Start typing your C/C++ solution below // DO NOT write int main() function int m = word1.size(); int n = word2.size(); vector<vector< int >> table(m+1,vector< int >(n+1, 0)); for ( int i = 1; i <= n; i++) table[0][i] = i; for ( int i = 1; i <= m; i++) table[i][0] = i; for ( int i = 1; i <= m; i++) for ( int j = 1; j <= n;j++) { int min1 = table[i-1][j] < table[i][j-1] ? table[i-1][j] : table[i][j-1]; min1++; int min2 = word1[i-1] == word2[j-1] ? 0 : 1; min2 += table[i-1][j-1]; table[i][j] = min1 < min2 ? min1 : min2; } return table[m][n]; } }; |
reference :http://www.geeksforgeeks.org/dynamic-programming-set-5-edit-distance/
--------------------------------------------------------------------天道酬勤!
【推荐】还在用 ECharts 开发大屏?试试这款永久免费的开源 BI 工具!
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步