D73 LeetCode 面试题 01.05.一次编辑(中等)
一、题目
二、思路(自己)
-
目前的想法是,先判断first和second的长度,分别标记为f和s 如果f=s,判断first到second是否是替换一个字符就能实现,或者是否相等 如果f>s,判断first到second是否删除一个字符就能实现:首先判断f是否比s大1,满足条件的话,就从f中从头到尾删一个字符,如果能匹配上一次,就证明能够删除一个字符就能实现。 如果f<s,判断first到second是否插入一个字符就能实现:与第二种情况相反,判断s是否比f大1,满足的话删除s中的字符。 第一次提交过程中出现如下错误
-
犯了一个特别低级的错误,就是判断String对象内容是否一样,应该使用equals方法,而非直接使用==,可能是有好几十天没写的原因了。继续加油吧! class Solution { public boolean oneEditAway(String first, String second) { int f=first.length(); int s=second.length(); if(f==s){ int count=0; for (int i = 0; i < f; i++) { if(first.charAt(i)!=second.charAt(i)) count++; } if(count>1) return false; else return true; }else if(f>s){ if(f!=s+1) return false; else { for (int i = 0; i < f; i++) { String s1=first.substring(0,i); String s2=first.substring(i+1,f); String s3=s1+s2; if(s3.equals(second)) return true; } return false; } }else { if(s!=f+1) return false; else { for (int i = 0; i < s; i++) { String s1=second.substring(0,i); String s2=second.substring(i+1,s); String s3=s1+s2; if(s3.equals(first)) return true; } return false; } } } } 三、题解(官方) 官方答案跟我的思路差不多,就是在判断删除或增加一个字符的方法不同 官方用的是 class Solution { public boolean oneEditAway(String first, String second) { int m = first.length(), n = second.length(); if (n - m == 1) { return oneInsert(first, second); } else if (m - n == 1) { return oneInsert(second, first); } else if (m == n) { boolean foundDifference = false; for (int i = 0; i < m; i++) { if (first.charAt(i) != second.charAt(i)) { if (!foundDifference) { foundDifference = true; } else { return false; } } } return true; } else { return false; } } public boolean oneInsert(String shorter, String longer) { int length1 = shorter.length(), length2 = longer.length(); int index1 = 0, index2 = 0; while (index1 < length1 && index2 < length2) { if (shorter.charAt(index1) == longer.charAt(index2)) { index1++; } index2++; if (index2 - index1 > 1) { return false; } } return true; } }