How to find the last repeated character in a string with Scala

1 Answer

0 votes
import scala.collection.mutable
import scala.util.boundary
import scala.util.boundary.break

object Main {

  // Finds the last repeated character in a string.
  // Scans the string from right to left using Scala 3's boundary/break mechanism.
  def findLastRepeatedCharacter(s: String): Char = {
    val seen = mutable.Set[Char]()

    boundary {
      for (c <- s.reverse) {
        // If the character is already in the set, break out and return it
        if (seen(c)) {
          break(c)
        }
        // Otherwise, record the character as seen
        seen += c
      }
      
      // Default return value if no duplicate is found (matching C++ style)
      ' '
    }
  }

  def main(args: Array[String]): Unit = {
    val testCases = List(
      "abca",
      "abcbd",
      "abcde",
      "abcdxypcbop",
      "abcdxypcbadom"
    )

    for (tc <- testCases) {
      val result = findLastRepeatedCharacter(tc)
      println(s"findLastRepeatedCharacter(\"$tc\") -> $result")
    }
  }
}


/*
run:

findLastRepeatedCharacter("abca") -> a
findLastRepeatedCharacter("abcbd") -> b
findLastRepeatedCharacter("abcde") ->  
findLastRepeatedCharacter("abcdxypcbop") -> p
findLastRepeatedCharacter("abcdxypcbadom") -> d

*/

 



answered 5 days ago by avibootz
...