一次编辑
难度:
标签:
题目描述
There are three types of edits that can be performed on strings: insert a character, remove a character, or replace a character. Given two strings, write a function to check if they are one edit (or zero edits) away.
Example 1:
Input: first = "pale" second = "ple" Output: True
Example 2:
Input: first = "pales" second = "pal" Output: False
代码结果
运行时间: 19 ms, 内存: 15.9 MB
/*
* 使用Java Stream判断字符串是否只需要一次编辑。
*/
import java.util.stream.IntStream;
public class OneEditAwayStream {
public static boolean isOneEditAway(String first, String second) {
if (Math.abs(first.length() - second.length()) > 1) return false;
String s1 = first.length() < second.length() ? first : second;
String s2 = first.length() < second.length() ? second : first;
long differences = IntStream.range(0, s1.length())
.filter(i -> s1.charAt(i) != s2.charAt(i + (s2.length() > s1.length() ? 1 : 0)))
.count();
return differences <= 1;
}
public static void main(String[] args) {
System.out.println(isOneEditAway("pale", "ple")); // True
System.out.println(isOneEditAway("pales", "pal")); // False
}
}
解释
方法:
该题解首先通过比较两个字符串的长度来确定较短和较长的字符串,并保证后续操作总是在长度小的字符串上进行。如果两个字符串的长度差超过1,则直接返回False,因为无法通过一次操作使二者相同。接着,根据两个字符串长度是否相等分别处理:如果长度相等,则通过比较每个对应位置的字符,统计不同字符的数量是否超过1;如果长度不相等(此时长度差为1),则通过一个偏移量ofs来比对较短字符串中的每个字符是否与较长字符串中的对应位置匹配,一旦发现不匹配,则增加偏移量,并检查是否超过1次编辑的机会。
时间复杂度:
O(n)
空间复杂度:
O(1)
代码细节讲解
🦆
在处理长度不相等的情况时,你是如何确保只通过单个偏移量`ofs`来正确处理插入或删除操作的?
▷🦆
当两个字符串长度相等时,你提到通过计数不同的字符来决定是否可以通过一次替换来修正,那么这种方法是否考虑了所有可能导致字符串不同的因素?
▷🦆
在算法中,如果长度差正好为1,为什么增加偏移量后不再检查之前已经比较过的字符,这样做的正确性如何保证?
▷