在列表中的重复对之间添加标记字符

Add a marker character between duplicate pair in list

我正在做一个练习,我需要弄清楚如何在列表中的两个重复元素之间添加指定的标记字符。

输入 - 一个字符串
输出 - 字符串对列表

两条规则;

  1. 如果输入的字符串有重复的字符,需要一个字符x 加在他们之间。例如; trees 将变为 tr, ex, es
  2. 如果重复的字符对是 xx,则在它们之间添加一个 q。例如; boxx 变为 bo,xq, x

两个规则运行一起输入,例如; 如果输入是 HelloScalaxxxx 输出应该是 List("He", "lx", "lo", "Sc", "al", "ax", "xq", "xq", "x")

我使用以下代码得到了第一条规则并努力使第二条规则得到满足。

 input.foldRight[List[Char]](Nil) {
      case (h, t) =>
        println(h :: t)
        if (t.nonEmpty) {
          (h, t.head) match {
            case ('x', 'x') => t ::: List(h, 'q')
            case _ => if (h == t.head) h :: 'x' :: t else h :: t
          }
        } else h :: t
    }
      .mkString("").grouped(2).toSeq

我想我很接近,因为输入 HelloScalaxxxx 它产生 List("He", "lx", "lo", "Sc", "al", "ax", "xq", "xq", "xq"),但在最后一对中有一个额外的 q

我不想使用基于正则表达式的解决方案。寻找惯用的 Scala 版本。

我尝试搜索现有答案,但没有成功。任何帮助,将不胜感激。谢谢。

我假设您想先应用 xx 规则...但您可以决定。

"Trees & Scalaxxxx"
  .replaceAll("(x)(?=\1)","q")
  .replaceAll("([^x])(?=\1)","x")
  .grouped(2).toList
//res0: List[String] = List(Tr, ex, es, " &", " S", ca, la, xq, xq, xq, x)

这是 non-regex 产品。

"Trees & Scalaxxxx"
  .foldLeft(('_',"")){
    case (('x',acc),'x')           => ('x', s"${acc}qx")
    case ((p,acc),c) if c == p && 
                        p.isLetter => ( c , s"${acc}x$c")
    case ((_,acc),c)               => ( c , s"$acc$c")
  }._2.grouped(2).toList

尾递归求解

def processString(input: String): List[String] = {
  @scala.annotation.tailrec
  def inner(buffer: List[String], str: String): List[String] = {
    // recursion ending condition. Nothing left to process
    if (str.isEmpty) return buffer

    val c0 = str.head
    val c1 = if (str.isDefinedAt(1)) {
      str(1)
    } else {
      // recursion ending condition. Only head remains.
      return buffer :+ c0.toString
    }

    val (newBuffer, remainingString) =
    (c0, c1) match {
      case ('x', 'x') =>          (buffer :+ "xq", str.substring(1))
      case (_, _)  if c0 == c1 => (buffer :+ s"${c0}x", str.substring(1))
      case _ =>                   (buffer :+ s"$c0$c1", str.substring(2))
    }
    inner(newBuffer, remainingString)
  }
  // start here. Pass empty buffer and complete input string
  inner(List.empty, input)
}

println(processString("trees"))
println(processString("boxx"))
println(processString("HelloScalaxxxx"))