字符串有三种编辑操作:插入一个字符、删除一个字符或者替换一个字符。 给定两个字符串,编写一个函数判定它们是否只需要一次(或者零次)编辑
输入:
first = "pale"
second = "ple"
输出: True
输入:
first = "pales"
second = "pal"
输出: False
解题思路:
分析:
- 两个字符串,如果长度相差2及以上,那么肯定是需要编辑两次的;
- 如果长度相差1,那么两个字符串肯定是只有一位是缺失,其它数都是对齐的,比如1234和124;
- 如果长度相同,那么两个字符串在对应位置上只能允许有一位不相同,比如1234和1235;
所以先搞定长度相差1的情况:
/**
* 因为只处理长度相差为1的两个字符串
* 分别给两个字符串定义一个指针
* 比较两个指针处的字符是否相同,如果不同,可以认为是缺失的那个字符,
* 那么短指针不动,长指针加1,再继续比较,只要指针相差2及以上,则两个字符串肯定有两处不同
*/
public static boolean checkOne(String longStr, String shortStr) {
//长字符串的长度
int len1 = longStr.length();
//短字符串的长度
int len2 = shortStr.length();
int index1 = 0;//长字符串的指针
int index2 = 0;//短字符串的指针
//指针没有越过边界就继续循环
while(index1 < len1 && index2 < len2) {
//当长字符串和短字符串在相应指针处字符相等
if (longStr.charAt(index1) == shortStr.charAt(index2)) {
//短字符串指针加1
index2++;
}
//长字符串指针加1
index1++;
//比较两个指针的位置,如果相差长度大于1,则说明位置有两处不一样
if (index1 - index2 > 1) {
return false;
}
}
return true;
}
再搞定长度相同的情况:
/**
* 处理相同长度的字符串
* 只需要比较相同位置的字符是否相同,不同的字符最多一个
*/
public static boolean checkSame(String str1, String str2){
int count = 0; //相同位置不同字符个数
for (int i = 0; i < str1.length(); i++) {
if (str1.charAt(i) != str2.charAt(i)) {
//相同位置字符不同就加1
count++;
}
//不同字符个数最多一个
if (count > 1) {
return false;
}
}
return true;
}
最后再统一下:
class Solution {
public boolean oneEditAway(String first, String second) {
int len1 = first.length();
int len2 = second.length();
if (len1 - len2 == 1) {
return checkOne(first, second);
} else if (len2 - len1 == 1) {
return checkOne(second, first);
} else if (len1 == len2) {
return chackSame(first, second);
}
//字符串长度超过2,则直接返回false
return false;
}
public static boolean checkOne(String longStr, String shortStr) {
int len1 = longStr.length();
int len2 = shortStr.length();
int index1 = 0;
int index2 = 0;
while(index1 < len1 && index2 < len2) {
if (longStr.charAt(index1) == shortStr.charAt(index2)) {
index2++;
}
index1++;
if (index1 - index2 > 1) {
return false;
}
}
return true;
}
/**
* 处理相同长度的字符串
* 只需要比较相同位置的字符是否相同,不同的字符最多一个
*/
public static boolean checkSame(String str1, String str2){
int count = 0; //相同位置不同字符个数
for (int i = 0; i < str1.length(); i++) {
if (str1.charAt(i) != str2.charAt(i)) {
//相同位置字符不同就加1
count++;
}
//不同字符个数最多一个
if (count > 1) {
return false;
}
}
return true;
}
}