Swift-对数组中每个字符串中的字符进行排序 [英] Swift - sorting characters in each string in an array
问题描述
因此,此问题是此问题的后续内容: swift字符串排列允许使用相同的字符串
So this question is a follow up to this one: swift string permutations allowing the same strings
在那里,我询问了我可以使用一组定义的字符串进行的所有可能的突变.我接下来要做的是过滤出具有相同组合但顺序不同的所有结果.
There, I asked about all possible mutations that I can make with a defined set of strings. What I am trying to do next is to filter out all results that have the same combination, but in a different order.
因此,如果输入为:["AB", "AC", "CA", "CB"]
,则输出应为["AB", "AC", "CB"]
,因为"AC"和"CA"具有相同的构造块.
So if the input is: ["AB", "AC", "CA", "CB"]
, the output should be ["AB", "AC", "CB"]
, since "AC" and "CA" have the same building blocks.
所以我的想法是先按字母顺序对每个字符串进行排序,然后再创建一个Set
.
So my thought was to first sort each string alphabetically, and maybe then create a Set
.
我已经停留在第一部分了:(
I am already stuck on the first part :(
let array = ["AB", "AC", "DC", "CA", "CB"]
print(type(of: array))
print(array)
let sortedArray = array.map{ $0.sorted() }
print(type(of: sortedArray))
print(sortedArray)
输出为:
Array<String>
["AB", "AC", "DC", "CA", "CB"]
Array<Array<Character>>
[["A", "B"], ["A", "C"], ["C", "D"], ["A", "C"], ["B", "C"]]
虽然我希望使用sortedArray:
While I expected for the sortedArray:
["AB", "AC", "CD", "AC", "BC"]
然后我想将各个字符串重新组合在一起:
Then I thought to join the individual strings back together:
print(array.map{ $0.joined() } )
产生ambiguous reference to member 'joined()'
但是我不知道如何解决这个问题.
But how to fix this I don't understand.
我也看到了这一点:将字符串中的字符快速排序其中使用以下代码:
I also saw this one: swift sort characters in a string where the following code is used:
var nonSortedString = "5121"
var sortedString = String(Array(nonSortedString.characters).sort())
但是我没有看到如何使用map
和朋友(转换为Swift 4之后)应用它
But I don't see how to apply that using map
and friends (after converting to Swift 4)
任何帮助表示赞赏.
推荐答案
如果要获取字符串,请对其字符进行排序,然后从中构建新的字符串,在Swift 4中,您可以:
If you want to take a string, sort its characters, and build a new string from that, in Swift 4 you can:
let string = "foobar"
let sortedString = String(string.sorted())
结果是:
讨厌"
因此,回到您的原始问题,您可以将字符串(是排列的集合)带到您的手中,并构建如下所示的组合排序数组:
So, going back to your original problem, you can take you strings, which are a collection of permutations, and build a sorted array of combinations like so:
let permutations = ["AB", "AC", "DC", "CA", "CB"]
// build set of combinations where each string has, itself, been sorted alphabetically
let combinations = Set(permutations.map { String($0.sorted()) })
// convert set (which removed duplicates) back to an array and sort it
let result = Array(combinations).sorted()
结果是:
["AB","AC","BC","CD"]
["AB", "AC", "BC", "CD"]
这篇关于Swift-对数组中每个字符串中的字符进行排序的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!