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


题目解析:

当a[i]和b[j]相等的时候,就判断a[i-1]和b[j-1]就行了。肯定取到最小值。如果不相等,就判断a[i-1]和b[j]、a[i-1]和b[j-1]、a[i]和b[j-1]三个,取最小的一个然后+1才是(i,j)的值!

代码过程中遇到两个问题,如何分配二维数组?如何释放二维数组?

先看代码,上面两个问题等会回答。

class Solution{
public:
    int minDistance(string word1,string word2){
        int len1 = word1.size();
        int len2 = word2.size();

        if(len1 == 0)   //直接
            return len2;
        if(len2 == 0)
            return len1;
            
        int **a;            //动态分配二维数组,其实通过解答,直接分配两个以为数组就行了,但是每次的以为数组的起始值是不一样的!
        a = new int*[len1+1];
        for(int i = 0;i <= len1;i++)
            a[i] = new int[len2+1];
            
        for(int i = 0;i <= len1;i++)      //初始化
            for(int j = 0;j <= len2;j++)
                a[i][j] = -1;

        for(int i = 0;i <= len1;i++)    //将第0行和第0列进行初始化,每一行的初始值是不一样的
            a[i][0] = i;
        for(int j = 0;j <= len2;j++)
            a[0][j] = j;

        for(int i = 1;i <= len1;i++){   //按照行遍历。
            for(int j = 1;j <= len2;j++){
                if(word1[i-1] == word2[j-1])
                    a[i][j] = a[i-1][j-1];
                else{
                    int min = a[i-1][j] < a[i-1][j-1] ? a[i-1][j] : a[i-1][j-1];
                    min = min < a[i][j-1] ? min : a[i][j-1];
                    a[i][j] = min + 1;
                }
            }
        }
        int temp = a[len1][len2];

        for(int i = 0;i <= len1;i++){   //释放内存空间
            delete []a[i];
            a[i] = NULL;
        }
        delete []a;
        a = NULL;
        return temp;
    }
};


下面回答上面的两个问题:

如何申请?

int i,j;
int **a; 
a=new int *[m];
for(i=0; i


如何释放?

for(int i = 0;i <= len1;i++){   //释放内存空间
            delete []a[i];
            a[i] = NULL;
        }
        delete []a;
        a = NULL;


多种方法:

C语言:

//二维数组动态数组分配和释放
//数组指针的内存分配和释放
//方法一
char (*a)[N];//指向数组的指针
a = (char (*)[N])malloc(sizeof(char [N]) * m);

free(a); 

//方法二
char **a;
int i;
a = (char **)malloc(sizeof(char *) * m);//分配指针数组
for(i=0; i

C++语言:

//二维数组动态数组分配和释放
//数组指针的内存分配和释放
//方法一
char (*a)[N];//指向数组的指针
a = new char[m][N];

delete[] a; 

//方法二
char **a;
a = new char* [m];//分配指针数组
for(int i=0; i


注意:

new和delete要注意配对使用,即有多少个new就有多少个delete,这样才可以避免内存泄漏!


参考链接:http://bbs.csdn.net/topics/390337580

http://blog.163.com/likunlunnihao@126/blog/static/118277127200952285824688/







你可能感兴趣的:(LeetCode)