题目:
Given two strings S and T, determine if they are both one edit distance apart.
题解:
分 长度差 等于1 大于1 等于0 三种情况。
C++版:
Python版:
Given two strings S and T, determine if they are both one edit distance apart.
题解:
分 长度差 等于1 大于1 等于0 三种情况。
C++版:
class Solution {
public:
bool isOneEditDistance(string s, string t) {
if(abs((int)(s.length() - t.length())) > 1)
return false;
if(s.length() == t.length()) {
bool diff = false;
for(int i = 0; i < s.length(); i++) {
if(s[i] != t[i]) {
if(!diff)
diff = true;
else
return false;
}
}
return diff == true;
}
if(s.length() > t.length())
swap(s, t);
int i = 0, j = 0, diff = 0;
while(i < s.length()) {
if(s[i] != t[j]) {
diff++;
if(diff > 1)
return false;
j++;
} else {
i++;
j++;
}
}
return true;
}
};
Java版:
public class Solution {
public boolean isOneEditDistance(String s, String t) {
if(Math.abs(s.length() - t.length()) > 1)
return false;
if(s.length() == t.length()) {
boolean diff = false;
for(int i = 0; i < s.length(); i++) {
if(s.charAt(i) != t.charAt(i)) {
if(!diff)
diff = true;
else
return false;
}
}
return diff == true;
}
if(s.length() > t.length()) {
String temp = s;
s = t;
t = temp;
}
int i = 0, j = 0, diff = 0;
while(i < s.length()) {
if(s.charAt(i) != t.charAt(j)) {
diff++;
if(diff > 1)
return false;
j++;
} else {
i++;
j++;
}
}
return true;
}
}
Python版:
from copy import copy
class Solution(object):
def isOneEditDistance(self, s, t):
"""
:type s: str
:type t: str
:rtype: bool
"""
if abs(len(s) - len(t)) > 1:
return False
if len(s) == len(t):
diff = False
for i in range(len(s)):
if s[i] != t[i]:
if not diff:
diff = True
else:
return False
if diff:
return True
else:
return False
if len(s) > len(t):
s, t = t, s
i, j, inserted = 0, 0, False
while i < len(s):
if s[i] != t[j]:
if inserted:
return False
else:
j += 1
inserted = True
else:
i += 1
j += 1
return True