在Scala中计算字符串的排列时堆栈溢出

时间:2013-09-08 18:26:28

标签: string scala permutation

所有都在标题中,代码在这里:

implicit class utils(val chaîne: String) {

    def permutations1(): List[String] = {
        if (chaîne.length() == 0) List()
        else
        if (chaîne.length() == 1) List(chaîne)
        else  {
            val retour1=for {i:Int <- 0 to chaîne.length() - 2
                 chaîne_réduite = chaîne.drop(i)
                 liste_avec_chaîne_réduite = chaîne_réduite.permutations1()
                 une_chaîne_réduite_et_permutée <- liste_avec_chaîne_réduite
                 j <- 0 to une_chaîne_réduite_et_permutée.length()
            }
            yield new StringBuilder(une_chaîne_réduite_et_permutée).insert(j, chaîne(j)).toString

            retour1.toList
        }
    }
}

你能解释一下为什么它不起作用并最终纠正我的代码以避免堆栈溢出吗?

2 个答案:

答案 0 :(得分:0)

不是问题NP-complete?因此,您只能使用非常有限的字符串长度运行任何代码。

为了使其在合理的字符串长度上工作,需要仔细优化。例如,为了提高性能,您可以尝试@tailrec优化。

StringStringBuilder形式的表示对于任务而言效率非常低。例如,尝试List的{​​{1}}。

答案 1 :(得分:0)

我自己找到了答案:

implicit class utils (val chaîne: String) {
  def permutations1 : Seq [String] = {
    if (chaîne.size == 1) Seq (chaîne)
    else chaîne.flatMap (x => chaîne.filterNot (_ == x).permutations1.map (x + _))
  }
}