Swift solution with comments (credit to @ChengZhang)


  • 0
    S
    class Solution {
        func isOneEditDistance(_ s: String, _ t: String) -> Bool {
            // easier to work with as string arrays
            let sc = Array(s.characters)
            let tc = Array(t.characters)
            
            // find the shortest of the 2 arrays
            let minlen = min(sc.count, tc.count)
            
            // iterate knowing we'll stop short of overflowing
            for i in 0..<minlen {
                if sc[i] != tc[i] {
                    if sc.count == tc.count {
                        // sc len == tc len, 
                        // check the remaining subarray for equality
                        return sc[(i+1)..<sc.count] == tc[(i+1)..<tc.count]
                    } else if sc.count < tc.count {
                        // tc is longer than sc, bump tc index by 1
                        // check the remaining subarray for equality
                        return sc[i..<sc.count] == tc[(i+1)..<tc.count]
                    } else {
                        // sc is longer than tc, bump sc index by 1
                        // check the remaining subarray for eqality
                        return sc[(i+1)..<sc.count] == tc[i..<tc.count]
                    }
                }
            }
            
            // everything matches, ensure the lengths are within 1
            return abs(sc.count - tc.count) == 1
        }
     }
    

Log in to reply
 

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