[Swift]LeetCode161. 一次編輯距離 $ One Edit Distance
阿新 • • 發佈:2018-12-12
Given two strings S and T, determine if they are both one edit distance apart.
給定兩個字串S和T,確定它們是否都是是一步變換得到的。
class Solution { func isOneEditDistance(_ s:String, _ t:String) -> Bool{ var num:Int = min(s.count, t.count) for i in 0..<num {if s.count == t.count { return s.substring(i + 1) == t.substring(i + 1) } else if s.count < t.count { return s.substring(i) == t.substring(i + 1) } else {return s.substring(i + 1) == t.substring(i) } } return abs(s.count - t.count) == 1 } } extension String { // 擷取字串:從index到結束處 // - Parameter index: 開始索引 // - Returns: 子字串 func substring(_ index: Int) -> String { let theIndex = self.index(self.endIndex, offsetBy: index - self.count)return String(self[theIndex..<endIndex]) } }