Edit Distance
来源:互联网 发布:mac上的音频剪辑软件 编辑:程序博客网 时间:2024/05/17 02:40
1.题目
给出两个单词word1和word2,计算出将word1 转换为word2的最少操作次数。
你总共三种操作方法:
- 插入一个字符
- 删除一个字符
- 替换一个字符
样例
给出 work1="mart" 和 work2="karma"
返回 3
2.算法
如果我们用 i 表示当前字符串 A 的下标,j 表示当前字符串 B 的下标。 如果我们用d[i, j] 来表示A[1, ... , i] B[1, ... , j] 之间的最少编辑操作数。那么我们会有以下发现:
1. d[0, j] = j;
2. d[i, 0] = i;
3. d[i, j] = d[i-1, j - 1] if A[i] == B[j]
4. d[i, j] = min(d[i-1, j - 1], d[i, j - 1], d[i-1, j]) + 1 if A[i] != B[j]
public static int minDistance(String word1, String word2) { if (word1.length() == 0) return word2.length(); if (word2.length() == 0) return word1.length(); int[][] distance = new int[word1.length() + 1][word2.length() + 1]; for (int i = 0; i <= word1.length(); i++) { distance[i][0] = i; } for (int i = 0; i <= word2.length(); i++) { distance[0][i] = i; } for (int i = 1; i <= word1.length(); i++) { for (int j = 1; j <= word2.length(); j++) { if (word1.charAt(i - 1) == word2.charAt(j - 1)) { distance[i][j] = distance[i-1][j-1]; } else { distance[i][j] = Math.min(distance[i-1][j], Math.min(distance[i][j-1], distance[i-1][j-1])) + 1; } //替换和插入 } } return distance[word1.length()][word2.length()]; }
public static int minDistance(String word1, String word2) { if (word1.length() == 0) return word2.length(); if (word2.length() == 0) return word1.length(); String minWord = word1.length()>word2.length()?word2:word1; String maxWord = word1.length()>word2.length()?word1:word2; int[] res = new int[minWord.length() + 1]; for (int i = 0; i <= minWord.length(); i++) { res[i] = i; //当另一个字符串为空时,需改变i + 1次 } for (int i = 0; i < maxWord.length(); i++)//res[i][j] = min(res[i-1][j], res[i][j-1], res[i-1][j-1])+1。 { int[] newRes = new int[minWord.length() + 1]; //对每个i建立一个数组j newRes[0] = i + 1; for (int j = 0; j < minWord.length(); j++) { if (minWord.charAt(j) == maxWord.charAt(i)) //res[i][j]=res[i-1][j-1] { newRes[j + 1] = res[j]; } else { //res[i][j] = min(res[i-1][j], res[i][j-1], res[i-1][j-1])+1。 newRes[j+1] = Math.min(res[j],Math.min(res[j+1],newRes[j]))+1; } } res = newRes; } return res[minWord.length()]; }
0 0
- edit distance
- Edit Distance
- edit distance
- Edit Distance
- Edit Distance
- Edit Distance
- Edit Distance
- Edit Distance
- Edit Distance
- Edit Distance
- Edit Distance
- Edit Distance
- Edit Distance
- Edit Distance
- Edit Distance
- Edit Distance
- Edit Distance
- Edit Distance
- C++转换函数
- HttpAsyncClient使用中碰到的问题
- HTTP学习笔记:状态码
- 神经网络训练中的Tricks之高效BP(反向传播算法)
- CentOS7 (精简操作指令)
- Edit Distance
- # dagger+retrofit+rxjava:框架搭建视频播放器:
- React.js官网的评论列表
- C语言动态内存管理
- win7激活一万遍都没解决的同学请看过来
- Android 中横屏竖屏设置
- dokan入门编译指南
- social-feed-box 社会评论模块(Bootstrap)
- 有思想的大脑,没灵性的AI