
思路:分为三个部分来做,delete,replace,insert。
delete很容易,只需要把长度大的那个string遍历remove每个元素,每remove一个元素,就和另一个string比较是否相等,如果想等就返回true。
replace也很容易,此时两个string必定是相等长度的,因为本题我们只修改s,以符合t,所以我们只需要将t中的每一个元素挨个替换s中的每一个元素,每替换一次,就进行一次比较,如相等,返回true。
insert,此时肯定是s比t长度小1,insert一个字母后两者相等。这里我们遍历t中的每一个元素,将他们分别插入到s中的每一个位置。每插入一次,比较一次,如相等,返回true。
说的很容易,实现起来还是比较麻烦的,特别是涉及到nested loop,时间复杂度会异常高,这也导致了我的答案最终并没有通过全部的test cases。系统告知我time limit exceeded。我的算法是没问题的,但是就是效率太低,超出了正常的时间复杂度。下面展示我的代码:
public boolean isOneEditDistance(String s, String t) {
String ss = s;
int len = s.length() - t.length();
if(len >= -1 && len <= 1){
if(s.length() > t.length()){
//delete
if(t.equals("")){
return true;
}else{
StringBuilder sb = new StringBuilder(s);
for(int i = 0; i < s.length(); i++){
sb.deleteCharAt(i);
String tmp = sb.toString();
if(tmp.equals(t)){
return true;
}else{
sb = new StringBuilder(ss);
}
}
return false;
}
}else if(s.length() == t.length()){
//replace
if(s.equals(t)){
return false;
}else{
for(int i = 0; i < t.length(); i++){
for(int j = 0; j< s.length(); j++){
String str = s.replace(s.charAt(j),t.charAt(i));
if(str.equals(t)){
return true;
}else{
s = ss;
}
}
}
return false;
}
}else{
//insert
if(s.equals("")){
return true;
}else{
StringBuffer sb = new StringBuffer(s);
for(int i = 0; i < t.length(); i++){
for(int j = 0; j < s.length(); j++){
sb.insert(j,t.charAt(i));
String str = sb.toString();
if(str.equals(t)){
return true;
}else{
sb = new StringBuffer(ss);
}
}
s = s + t.charAt(i);
if(s.equals(t)){
return true;
}else{
s = ss;
}
}
return false;
}
}
}else{
return false;
}
}
下面给出官方标答,是现实很简单,主要还是算法比较好下面我给出官方的算法,以及代码:



int sl = s.length();
int tl = t.length();
// Ensure that s is shorter than t.
if(sl - tl > 0){
return isOneEditDistance(t,s);
}else{
// The strings are NOT one edit away distance
// if the length diff is more than 1.
if(tl - sl > 1){
return false;
}else{
for(int i = 0; i< sl; i++){
if(s.charAt(i) != t.charAt(i)){
// if strings have the same length
if(sl == tl)
return s.substring(i+1).equals(t.substring(i+1)); //replace
// if strings have different lengths
else
return s.substring(i).equals(t.substring(i+1)); //delete
}
}
// If there is no diffs on ns distance
// the strings are one edit away only if
// t has one more character.
return (sl + 1 == tl); //insert
}
}
总结:
- remove a single character a string:StringBuilder.deleteCharAt()
- append a single character at the end of a string: string builder.append(char/str) or string= string + char/str
- append a single character to a given index of a string: stringbuilder.insert(index,str/char)
- convert StringBuffer to String: string buffer.toString()
- compare whether two strings are equal: str1.equal(str2)
- compare whether two char are equal: char1 == char2
本文深入探讨了一编辑距离算法的实现细节,包括删除、替换和插入三种操作,并对比了自定义算法与官方算法的效率,强调了算法优化的重要性。
753

被折叠的 条评论
为什么被折叠?



