String 在Scala中计算置换或字符串时堆栈溢出

String 在Scala中计算置换或字符串时堆栈溢出,string,scala,permutation,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:

所有内容都在标题中,代码如下:

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
        }
    }
}
隐式类utils(val chaîne:String){
def排列1():列表[字符串]={
如果(chaîne.length()=0)列表()
其他的
if(chaîne.length()=1)列表(chaîne)
否则{
val retour1=for{i:Int不是问题吗?因此,您只能运行字符串长度非常有限的代码

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


String
StringBuilder
的形式表示对于任务来说效率很低。例如,尝试
字符的
列表

我自己找到了一个答案:

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 + _))
  }
}

但问题不在于时间,而在于内存空间太大。我可以证明这是可以做到的:在scala.collections中,有一种置换方法,可以在字符串的所有置换上创建迭代器(但我想自己做!)绝对不是NP完全的,更糟糕的是,因为输出大小不是输入大小的多项式。但是,对于相当小的输入,可以这样做。问题是即使是短字符串也会出现无止境的循环,而不是NP完全性之类的。“xy”.permutions1已经引发了异常。ZipWithIndex返回一个元组的indexedSeq,因此要对其进行平面映射,您需要一个接受char和int元组的函数,最好的方法是
chaîne.ZipWithIndex flatMap{case(x:char,i:int)=>chaîne.drop(i).permutions2.map(x+}
,但我想这会让人困惑you@gourlaysama:是的,我也认为,但是,作为stackoverflow的新手,我不知道如何突出显示行标题受尊重的注释中的代码;@alexlv:我尝试过,但我有一个堆栈溢出错误,这段代码有效:`def permutations3:Seq[String]={if(chaîne.size==1)Seq(chaîne);else chaîne.flatMap(x=>chaîne.filterNot(==x).permutations3.map(x+);)`天哪!有可能让注释代码的格式像answers的代码一样吗?@alexlv:我给了你一个工作代码,但它有一个默认值:它只处理没有重复字符的字符串,我想通过更改工作示例,让代码可以处理所有字符串(即使我应该在排列搜索结束时删除重复项,但这是另一回事)@alex:你知道如何避免堆栈溢出错误吗?或者为什么会发生这种错误?你能解释一下代码,它应该如何工作吗?顺便说一句:法语标识符使得获取代码和测试/修改代码变得很困难,因为它具有奇特的字符。好的:方法排列1被添加到字符串类中;在一些小情况(0和1)之后一般情况下的处理包括提取每个字符,并在所有剩余字符的所有可能位置替换它。我建议您考虑我给出的另一个答案,因为它看起来更简单和更短。