• + 0 comments

    Solution on Scala. It is based on Map ("indexedMap"). In which key is a char, which is present such in word and pat-candidate. And value is list of char order indexes. Each index is consistently incremented, when character of pat is found in word. For example, word "videobox" for pat "videobox" represented as ("v"->List(0), "i"->List(1),"d"->List(2),"e"->List(3),"0"->List(4,6),"b"->List(5),"x"->List(7)). Using this map, consistently compare indexes of pat-candidate with indexes of word in order to find the order. Order is detected, where the difference between indexes equals one (for example 6 and 5). If an order is detected for all characters in pat-candidate, pat is confirmed.

    `case class T(text: String, pat: String)
    
    class Solution {
    
     def findPats(casesNumber: Int, cases: List[T]) = {
    
    def findPat(testCase: T) = {
      def findOrder(curIndList: List[Int], prevIndList: List[Int]): Boolean = {
        val rez = for {
          c<-curIndList
          p<-prevIndList
          if (p - c == 1) || (c - p == 1)
        } yield c
      rez.nonEmpty
      }
    
      @tailrec
      def indexedMap(text: List[Char], cMap: Map[Char, List[Int]], index: Int): Map[Char, List[Int]] = text match {
        case c::_ if cMap.contains(c) && text.nonEmpty =>
          val updatedMap = cMap + (c -> cMap(c).::(index + 1))
          indexedMap(text.tail, updatedMap, index + 1)
        case c::_ if !cMap.contains(c) && text.nonEmpty =>
          val updatedMap = cMap + (c -> List((index + 1)))
          indexedMap(text.tail, updatedMap, index + 1)
        case _ => cMap
      }
    
      val textMap = indexedMap(testCase.text.toList, Map.empty[Char, List[Int]], -1)
      val firstOcc = List(textMap.getOrElse(testCase.pat.head, List(0)))
      val rez = testCase.pat.foldLeft((List(testCase.pat.head), firstOcc)) {
        (acc, el) => {
          val curIndList = textMap.getOrElse(el, List(0))
          val append = if (acc == firstOcc || findOrder(curIndList, acc._2.last)) (acc._1:+el, acc._2:+curIndList) else acc
          append
        }
      }._1
      if (rez.length == testCase.pat.length) println("YES") else println("NO")
    }
    
    cases.foreach(findPat)
     }
    }`