在线时间:8:00-16:00
迪恩网络APP
随时随地掌握行业动态
扫描二维码
关注迪恩网络微信公众号
★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★ Strings Given two anagrams Example 1: Input: A = 1
Example 2: Input: A = 2
Example 3: Input: A = 2
Example 4: Input: A = 2
Note:
如果可以通过将 给定两个字母异位词 示例 1: 输入:A = "ab", B = "ba" 输出:1 示例 2: 输入:A = "abc", B = "bca" 输出:2 示例 3: 输入:A = "abac", B = "baca" 输出:2 示例 4: 输入:A = "aabc", B = "abca" 输出:2 提示:
Runtime: 256 ms
Memory Usage: 20.4 MB
1 class Solution { 2 func kSimilarity(_ A: String, _ B: String) -> Int { 3 if A == B {return 0} 4 var arrB:[Character] = Array(B) 5 var vis:Set<String> = Set<String>() 6 var q:[String] = [String]() 7 q.append(A) 8 vis.insert(A) 9 var res:Int = 0 10 while(!q.isEmpty) 11 { 12 res += 1 13 for sz in stride(from:q.count,to:0,by:-1) 14 { 15 var s:String = q.removeFirst() 16 var arrS:[Character] = Array(s) 17 var i:Int = 0 18 while(arrS[i] == arrB[i]) 19 { 20 i += 1 21 } 22 for j in (i + 1)..<s.count 23 { 24 if arrS[j] == arrB[j] || arrS[i] != arrB[j] 25 { 26 continue 27 } 28 var temp:String = swap(s, i, j) 29 if temp == B {return res} 30 if !vis.contains(temp) 31 { 32 vis.insert(temp) 33 q.append(temp) 34 } 35 } 36 } 37 } 38 return res 39 } 40 41 func swap(_ s:String,_ i:Int,_ j:Int) -> String 42 { 43 var arrS:[Character] = Array(s) 44 arrS.swapAt(i,j) 45 return String(arrS) 46 } 47 }
|
请发表评论