LeetCode - One Edit Distance
Given two strings S and T, determine if they are both one edit distance apart.
1. 两个字符串的长度之差大于1,那么直接返回False
2. 两个字符串的长度之差等于1,那么长的那个字符串去掉一个字符,剩下的应该和短的字符串相同
3. 两个字符串的长度之差等于0,那么两个字符串对应位置的字符只能有一处不同。
public class Solution {
public static void main(String[] args){
String s = "test1";
String t = "test12";
System.out.println(isOneEditDistance(s,t));
}
public static boolean isOneEditDistance(String s, String t) {
int sl = s.length();
int tl = t.length();
if(Math.abs(sl - tl)>1){
return false;
}
if(sl - tl == 1){
return isDeleteOne(s, t);
}
if(tl - sl == 1){
return isDeleteOne(t,s);
}
if(tl == sl){
return isEditOne(s, t);
}
return false;
}
public static boolean isDeleteOne(String sLong, String sShort){
for(int i=0; i<sLong.length(); i++){
String subStr = "";
if(i == 0){
subStr = sLong.substring(1);
}
else if(i == sLong.length()-1){
subStr = sLong.substring(0,sLong.length()-1);
}
else{
subStr = sLong.substring(0,i)+sLong.substring(i+1,sLong.length()-1);
}
if(subStr.equals(sShort)){
return true;
}
}
return false;
}
public static boolean isEditOne(String s, String t){
boolean modified = false;
for (int i=0; i<s.length(); i++){
if(s.charAt(i) != t.charAt(i)){
if(modified){
return false;
}
modified = true;
}
}
return modified;
}
}
posted on 2018-07-10 10:42 IncredibleThings 阅读(101) 评论(0) 收藏 举报
浙公网安备 33010602011771号