面试题01.05. 一次编辑
01.05. 一次编辑
1、题目
字符串有三种编辑操作:插入一个字符、删除一个字符或者替换一个字符。 给定两个字符串,编写一个函数判定它们是否只需要一次(或者零次)编辑。
1)示例1
输入: first = "pale" second = "ple" 输出: True
2) 示例2
输入: first = "pales" second = "pal" 输出: False
2、初步作答
2.1 思路
- 能够一次编辑一个字符成功
- 两个字符串长度相差一定为1,是通过删除或者添加操作
- 字符串长度相差为0,是通过替换操作
- 去除多余的字符,再将两个字符串进行比较是否完全相同
2.2 做法
- 比较字符串长度之差是否小于等于 1,不是返回false
- 将字符串转为字符数组,字符串长度大的为字符串数组 s1,小的为 s2,并把小的数组加到一个长度与 s1 相同的数组 s3 中
- 比较第一个不同的字符,去除 s1中的这一字符,形成新的字符数组 s1
- 比较 s2 和 s3 是否相同,不同返回false,相同返回true
2.3 代码
package InterView01_05Primary_editing;
import static java.lang.Math.*;
public class Primary_editing {
public static void main(String[] args) {
String s1,s2;
s1 = "slander";
s2 = "islander";
System.out.println(s1.equals(s2));
boolean a = oneEditAway(s1,s2);
System.out.println(a);
}
public static boolean oneEditAway(String first, String second) {
boolean a;
int f = first.length();
int se = second.length();
if(first.isEmpty() && second.isEmpty() ){
return true;
}
if((first.isEmpty()==true && second.isEmpty()==false)||((first.isEmpty()==false && second.isEmpty()==true))){
return true;
}
if (Math.abs((f-se)) > 1) {
return false;
}
char[] s1 = new char[Math.max(f,se)];
char[] s2 = new char[Math.max(f,se)];
char[] s3 = new char[Math.max(f,se)];
if (f>se) {
s1 = first.toCharArray();
s2 = second.toCharArray();
for(int i=0;i
执行用时:1 ms, 在所有 Java 提交中击败了99.88%的用户 |
---|
内存消耗:40.9 MB, 在所有 Java 提交中击败了14.17%的用户 |
通过测试用例:1146 / 1146 |
2.4 思考
本题是采用暴力解法进行操作,通过判断字符数组之间差异的个数,来确定是否进行一次以内的操作就可以进行。
3、其余解法
来自力扣作者:jyd
class Solution {
public boolean oneEditAway(String first, String second) {
int lf = first.length(), ls = second.length();
if (lf > ls)
return oneEditAway(second, first);
if (ls - lf > 1)
return false;
if (lf == ls) {
int count = 0;
for (int i = 0; i < lf; i++) {
if (first.charAt(i) != second.charAt(i))
count += 1;
}
return count <= 1;
}
int i = 0, ofs = 0;
while (i < lf) {
if (first.charAt(i) != second.charAt(i + ofs)) {
if (++ofs > 1)
return false;
} else {
i += 1;
}
}
return true;
}
}