美文网首页
Swift-字符串排列

Swift-字符串排列

作者: FlyElephant | 来源:发表于2017-05-30 00:51 被阅读168次

    题目:确定某字符串的全部排列组合.

    核心代码:

       func getPerms(str:String) -> [String] {
            
            var permutations:[String] = []
            
            if str.characters.count == 0 {
                permutations.append("")
                return permutations
            }
            
            let first:String = str[0]
            let index = str.index(str.startIndex, offsetBy: 1)
            let remainder:String = str.substring(from: index)
            let words:[String] = getPerms(str: remainder)
            
            for word in words {
                
                for i in 0...word.characters.count {
                    let str:String = insertCharAt(word: word, mid: first, i: i)
                    permutations.append(str)
                }
            }
            
            return permutations
        }
        
        func insertCharAt(word:String,mid:String,i:Int) -> String {
            let index = word.index(word.startIndex, offsetBy: i)
            let start:String = word.substring(to: index)
            let end:String = word.substring(from: index)
            let result = start + mid + end
            
            return result
        }
    

    测试代码:

    var permutations:[String] = recursion.getPerms(str: "abc")
    print("FlyElephant---字符串排列:\(permutations)")
    
    FlyElephant.png

    相关文章

      网友评论

          本文标题:Swift-字符串排列

          本文链接:https://www.haomeiwen.com/subject/ewgkfxtx.html