Swift solution using String indices (46ms, beating 100% now)


  • 0
    S

    Using Swift String's indices instead of [Character] conversion is faster and doesn't use extra memory.

    class Solution {
        func isOneEditDistance(_ s: String, _ t: String) -> Bool {
            let diff = s.characters.count - t.characters.count
            
            if diff == 0 {
                var si = s.startIndex, ti = t.startIndex
                var replaced = false
                while si < s.endIndex {
                    if s[si] != t[ti] {
                        if replaced { return false }
                        replaced = true
                    }
                    si = s.index(after: si)
                    ti = t.index(after: ti)
                }
                return replaced
            } else if diff == 1 || diff == -1 {
                let shorter = diff < 0 ? s : t, longer = diff > 0 ? s : t
                var si = shorter.startIndex, li = longer.startIndex
                var skipped = false
                while si < shorter.endIndex {
                    if shorter[si] != longer[li] {
                        if skipped { return false }
                        li = longer.index(after: li)
                        skipped = true
                    } else {
                        li = longer.index(after: li)
                        si = shorter.index(after: si)
                    }
                    
                }
                return true
            }
            return false
        }
    }
    

Log in to reply
 

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