[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

 

这题真是火大啊,犯了个低级错误,在private里开了个f[1000][1000],然后每次都memset(f, 0, sizeof(f))一下,本来以为开销不大,没想到大数据一直超时,始终找不到问题,

想想算法没错呀,O(n^2)应该是最低了,没想到是memset搞得鬼,以后真是不能随便一个memset了。

 1 class Solution {
 2 public:
 3     int minDistance(string word1, string word2) {
 4         // Start typing your C/C++ solution below
 5         // DO NOT write int main() function
 6         vector<vector<int> > f(word1.size()+1, vector<int>(word2.size()+1));
 7         
 8         f[0][0] = 0;
 9         for(int i = 1; i <= word2.size(); i++)
10             f[0][i] = i;
11         
12         for(int i = 1; i <= word1.size(); i++)
13             f[i][0] = i;
14             
15         for(int i = 1; i <= word1.size(); i++)
16             for(int j = 1; j <= word2.size(); j++)
17             {
18                 f[i][j] = INT_MAX;
19                 if (word1[i-1] == word2[j-1]) 
20                     f[i][j] = f[i-1][j-1];
21                 
22                 f[i][j] = min(f[i][j], f[i-1][j-1] + 1); //replace
23                 f[i][j] = min(f[i][j], min(f[i-1][j], f[i][j-1]) + 1); //delete or insert               
24             }
25             
26         return f[word1.size()][word2.size()];
27     }
28 };
posted @ 2012-11-06 20:06  chkkch  阅读(966)  评论(0编辑  收藏  举报