字符串有三种编辑操作:插入一个字符、删除一个字符或者替换一个字符。 给定两个字符串,编写一个函数判定它们是否只需要一次(或者零次)编辑。
示例 1:
输入:
first = “pale”
second = “ple”
输出: True
示例 2:
输入:
first = “pales”
second = “pal”
输出: False
题解:
class Solution {
public boolean oneEditAway(String first, String second) {
if(first == null && second == null || first.length() == 0 && second.length() == 0){
return true;
}
if(first == null && second != null || first != null && second == null){
return false;
}
return editTime(first, second) <= 1 ? true : false;
}
public int editTime(String str1, String str2) {
int len1 = str1.length();
int len2 = str2.length();
int[][] dp = new int[len1+1][len2+1];
dp[0][0] = 0; // 表示空字符串的时候
for(int i=1; i<= len1; i ++){
dp[i][0] = dp[i-1][0] + 1;
}
for(int i=1; i<= len2; i ++){
dp[0][i] = dp[0][i-1] + 1;
}
for(int i = 1; i<= len1; i++){
for(int j = 1; j<= len2; j++){
if(str1.charAt(i-1) == str2.charAt(j-1)){
dp[i][j] = dp[i-1][j-1];
}else{
dp[i][j] = Math.min(Math.min(dp[i-1][j], dp[i-1][j-1]), dp[i][j-1]) + 1;
}
}
}
return dp[len1][len2];
}
}