My solutions in 3 languages with one for loop


  • 16

    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

  • 0
    A

    This is brilliant!!


  • -1
    A

    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.


  • 0

  • 4

    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
    

  • 1
    K

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


  • 0

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


Log in to reply
 

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