You are viewing a single comment's thread. Return to all comments →
scala:
import scala.io.StdIn import scala.annotation.tailrec object Solution { private def longestPrefixSuffix(pat: String): Seq[Int] = { val m = pat.length val lps = Array.fill(m)(0) @tailrec def calculate(patIdx: Int, prevIdx: Int): Unit = { if (patIdx < m) { if (pat(patIdx) == pat(prevIdx)) { lps(patIdx) = prevIdx + 1 calculate(patIdx + 1, prevIdx + 1) } else if (prevIdx != 0) calculate(patIdx, lps(prevIdx - 1)) else { lps(patIdx) = 0 calculate(patIdx + 1, prevIdx) } } } calculate(1, 0) lps.toSeq } private def kmpSearch(txt: String, pat: String): String = { val n = txt.length val m = pat.length val lps = longestPrefixSuffix(pat) @tailrec def search(txtIdx: Int, patIdx: Int): String = { if (n <= txtIdx) "NO" else if (pat(patIdx) == txt(txtIdx)) { if (patIdx == (m - 1)) "YES" else search(txtIdx + 1, patIdx + 1) } else if (patIdx == 0) search(txtIdx + 1, patIdx) else search(txtIdx, lps(patIdx - 1)) } search(0, 0) } def main(args: Array[String]): Unit = { val in = Iterator .continually(StdIn.readLine()) .takeWhile(null != _) val t = in.next().toInt (1 to t) .map(_ => kmpSearch(in.next(), in.next())) .foreach(println) } }
Seems like cookies are disabled on this browser, please enable them to open this website
Substring Searching
You are viewing a single comment's thread. Return to all comments →
scala: