本文介绍了打印出字符串的所有组合的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

iOS 11,Swift 4.0

iOS 11, Swift 4.0

尝试编写一个递归函数以显示字符串的所有可能组合.我知道了,但由于我只得到20对,我应该得到24对,所以不太正确.我看不到我在这里错过的一切.

Trying to write a recursive function to show all the possible combinations of a string. I got this, but its not quite right since I get only 20 pairs and I should get 24. I cannot see what I have missed here.

该编码在哪里出错?

var ans:Set<String>!

override func viewDidLoad() {
    super.viewDidLoad()
    // Do any additional setup after loading the view, typically from a nib.
    let str = "ABCD"
    ans = []
    recursiveString(s2s: str, char2s: 0)
    print("\(ans) \(ans.count)")
}

func recursiveSwap(s2x: String, c2x: Int, j2m: Int) {
    var anschr = Array(s2x)
        let tmpchr = anschr[c2x]
        anschr[c2x] = anschr[c2x+j2m]
        anschr[c2x+j2m] = tmpchr
        print("\(String(anschr))")
            ans.insert(String(anschr))
        if (c2x + j2m + 1) < s2x.count {
            recursiveSwap(s2x: String(s2x), c2x: c2x, j2m: j2m+1)
        } else {
            if (c2x + 1) < s2x.count - 1 {
                recursiveSwap(s2x: String(anschr), c2x: c2x + 1, j2m: 1)
            }
        }
}

func recursiveString(s2s: String, char2s: Int) {
    let blue = shiftString(s2s: s2s)
    if char2s < s2s.count {
        recursiveSwap(s2x: blue, c2x: 0, j2m: 1)
        recursiveString(s2s: blue, char2s: char2s + 1)
    }
}

func shiftString(s2s: String) -> String {
    let str2s = Array(s2s)
    let newS = str2s.suffix(str2s.count - 1)  + str2s.prefix(1)
    return String(newS)
}

给我...

CBDADCBA交流数据库ADCBABDCA B C DDCABADCB数模转换器南部非洲发展共同体计算机辅助设计BCDA公元前南部非洲发展共同体中央商务区工商管理学院CDBACDABBACD工商管理学院DBCADCBA数模转换器DABC

CBDADCBAACDBADCBABDCABCDDCABADCBBDACBADCBCADBCDAADBCBADCCABDCBADCDBACDABBACDCBADDBCADCBADACBDABC

推荐答案

不是您问题的直接答案,但您可以获取所有排列(从Java转换为Swift),如下所示:

Not a direct answer to your question but you can get all permutations (translated from java to Swift) as follow:

public extension RangeReplaceableCollection {
    func permutations() -> [SubSequence] {
        isEmpty ? [] : permutate(.init())
    }
    private func permutate(_ subSequence: SubSequence) -> [SubSequence] {
        var permutations = isEmpty ? [subSequence] : []
        indices.forEach {
            permutations += (self[..<$0] + self[$0...].dropFirst())
                .permutate(subSequence + CollectionOfOne(self[$0]))
        }
        return permutations
    }
}


let str = "ABCD"
print(str.permutations())   // "["ABCD", "ABDC", "ACBD", "ACDB", "ADBC", "ADCB", "BACD", "BADC", "BCAD", "BCDA", "BDAC", "BDCA", "CABD", "CADB", "CBAD", "CBDA", "CDAB", "CDBA", "DABC", "DACB", "DBAC", "DBCA", "DCAB", "DCBA"]\n"


对子字符串进行突变


Per-mutating a substring

print("ABCD".dropLast().permutations())   // ["ABC", "ACB", "BAC", "BCA", "CAB", "CBA"]\n"

这篇关于打印出字符串的所有组合的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

09-02 15:34