String Edit Distance(DP)

description:
Two strings \(a,b\) are nonempty strings.We can replace a char, delete a char or add a char, so how many edition are needed to make the two strings the same?
solution:
We consider the empty string and another string. Either by adding \(strlen\) times, or deleting \(strlen\) times, we can make them the same. In orther words, the distance is \(strlen\)

Then use the recursion below:

\(f[i][j]=min(f[i-1][j-1]+[a[i] \neq b[j]], f[i][j-1]+1, f[i-1][j]+1)\)
(replace or no need to repalce; delete a's end, delete b's end. Get the minimum.

Experience:
1.strings: the prefix. \(\rightarrow\) a 2-dimension table.
2.The symmetrical property of delete and add.
code:

#include<cstdio>
#include<cstring>
int main() {
	int t;
	scanf("%d", &t);
	while (t--) {
		char a[22], b[22];
		scanf("%s%s", a + 1, b + 1);
		int la = strlen(a + 1), lb = strlen(b + 1);
		int f[22][22];
		for (int i = 0; i <= la; ++i)
			f[i][0] = i;
		for (int i = 0; i <= lb; ++i)
			f[0][i] = i;
		for (int i = 1; i <= la; ++i)
			for (int j = 1; j <= lb; ++j) {
				int t1 = f[i - 1][j - 1];
				if (a[i] != b[j])++t1;
				int t2 = f[i][j - 1]+1;
				int t3 = f[i - 1][j]+1;
				if (t1 > t2)t1 = t2;
				if (t1 > t3)t1 = t3;
				f[i][j] = t1;
			}
		printf("%d\n", f[la][lb]);
	}
}
posted @ 2021-02-26 16:10  _dwt  阅读(37)  评论(0)    收藏  举报