# My solutions in 3 languages with one for loop

• Java:

``````for (int i = 0; i < Math.min(s.length(), t.length()); i++) {
if (s.charAt(i) != t.charAt(i)) {
return s.substring(i + (s.length() >= t.length() ? 1 : 0)).equals(t.substring(i + (s.length() <= t.length() ? 1 : 0)));
}
}
return Math.abs(s.length() - t.length()) == 1;
``````

C++:

``````    for (int i = 0; i < min(s.size(), t.size()); i++) {
if (s.at(i) != t.at(i)) {
return s.substr(i + (s.size() >= t.size() ? 1 : 0)).compare(t.substr(i + (s.size() <= t.size() ? 1 : 0))) == 0;
}
}
return s.size() - t.size() == 1 || s.size() - t.size() == -1;
``````

Python:

``````    for i in range(min(len(s), len(t))):
if s[i] != t[i]:
return s[i + (1 if len(s) >= len(t) else 0):] == t[i + (1 if len(s) <= len(t) else 0):]
return abs(len(s) - len(t)) == 1``````

• This is brilliant!!

• Elegant code. But there is one minor issue in your last line:

s.size() and t.size() both return unsigned int. The subtraction may not be -1 as you would expect. s = "" and t = "A" may fail this test.

• Nicer Python:

``````def isOneEditDistance(self, s, t):
d = len(s) - len(t)
for i, (a, b) in enumerate(zip(s, t)):
if a != b:
return s[i+(d>=0):] == t[i+(d<=0):]
return abs(d) == 1
``````

• Very simple and neat code. But is not very readable.

• Excellent solution. I actually fount it very readable and simple. (Want unreadable code? Check out those bit-manipulation questions)

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.