Calculate all permutations of a string in Swift

后端 未结 8 1357
余生分开走
余生分开走 2020-12-03 03:28

For the string \"ABC\" the code snippet below calculates 5 of the 6 total permutations. My strategy was to insert each character at each index possible index. B

8条回答
  •  一个人的身影
    2020-12-03 03:58

    Apple today released an Algorithms package available at:

    https://github.com/apple/swift-algorithms

    This package includes a permutations function that works like so:

    let string = "abc"
    string.permutations()
    /*
    ["a", "b", "c"]
    ["a", "c", "b"]
    ["b", "a", "c"]
    ["b", "c", "a"]
    ["c", "a", "b"]
    ["c", "b", "a"]
    */
    

提交回复
热议问题