Calculate all permutations of a string in Swift

后端 未结 8 1346
余生分开走
余生分开走 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条回答
  •  Happy的楠姐
    2020-12-03 04:17

    A very straightforward approach as also suggested in Swift coding challenges.

     func permutation(string: String, current: String = "") {
            let length = string.characters.count
            let strArray = Array(string.characters)
            if (length == 0) {
                // there's nothing left to re-arrange; print the result
                print(current)
                print("******")
            } else {
                print(current)
                // loop through every character
                for i in 0 ..< length {
                    // get the letters before me
                    let left = String(strArray[0 ..< i])
                    // get the letters after me
                    let right = String(strArray[i+1 ..< length])
                    // put those two together and carry on
                    permutation(string: left + right, current: current +
                        String(strArray[i]))
                }
    
            }
        }
    

提交回复
热议问题