[Swift]LeetCode854. 相似度为 K 的字符串 | K-Similar Strings
★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★
➤微信公众号:山青咏芝(shanqingyongzhi)
➤博客园地址:山青咏芝(https://www.cnblogs.com/strengthen/)
➤GitHub地址:https://github.com/strengthen/LeetCode
➤原文地址: https://www.cnblogs.com/strengthen/p/10593474.html
➤如果链接不是山青咏芝的博客园地址,则可能是爬取作者的文章。
➤原文已修改更新!强烈建议点击原文地址阅读!支持作者!支持原创!
★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★
Strings A
and B
are K
-similar (for some non-negative integer K
) if we can swap the positions of two letters in A
exactly K
times so that the resulting string equals B
.
Given two anagrams A
and B
, return the smallest K
for which A
and B
are K
-similar.
Example 1:
Input: A = "ab", B = "ba"
Output: 1
Example 2:
Input: A = "abc", B = "bca"
Output: 2
Example 3:
Input: A = "abac", B = "baca"
Output: 2
Example 4:
Input: A = "aabc", B = "abca"
Output: 2
Note:
1 <= A.length == B.length <= 20
A
andB
contain only lowercase letters from the set{'a', 'b', 'c', 'd', 'e', 'f'}
如果可以通过将 A
中的两个小写字母精确地交换位置 K
次得到与 B
相等的字符串,我们称字符串 A
和 B
的相似度为 K
(K
为非负整数)。
给定两个字母异位词 A
和 B
,返回 A
和 B
的相似度 K
的最小值。
示例 1:
输入:A = "ab", B = "ba" 输出:1
示例 2:
输入:A = "abc", B = "bca" 输出:2
示例 3:
输入:A = "abac", B = "baca" 输出:2
示例 4:
输入:A = "aabc", B = "abca" 输出:2
提示:
1 <= A.length == B.length <= 20
A
和B
只包含集合{'a', 'b', 'c', 'd', 'e', 'f'}
中的小写字母。
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 }