Given two strings S and T, determine if they are both one edit distance apart.
一刷
题解:只会有三种情况
- Replace 1 char:
s: a B c
t: a D c - Delete 1 char from s:
s: a D b c
t: a b c - Delete 1 char from t
s: a b c
t: a D b c
public class Solution {
public boolean isOneEditDistance(String s, String t) {
int len = Math.min(s.length(), t.length());
for(int i=0; i<len; i++){
if(s.charAt(i) != t.charAt(i)){
if(s.length() == t.length()){
return s.substring(i+1).equals(t.substring(i+1));
}
if(s.length()<t.length()){//delete one char in s
return s.substring(i).equals(t.substring(i+1));
}
else{
return t.substring(i).equals(s.substring(i+1));
}
}
}
return Math.abs(s.length() - t.length())==1;
}
}
二刷
思路同上
public class Solution {
public boolean isOneEditDistance(String s, String t) {
int len = Math.min(s.length(), t.length());
for(int i=0; i<len; i++){
if(s.charAt(i)!=t.charAt(i)){
if(s.length() == t.length()) return s.substring(i+1).equals(t.substring(i+1));
else if(s.length() > t.length()) return s.substring(i+1).equals(t.substring(i));
else return s.substring(i).equals(t.substring(i+1));
}
}
return Math.abs(s.length()-t.length())==1;
}
}```