Last active
December 20, 2015 01:09
-
-
Save mzkrelx/6047417 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| import scala.collection.mutable.ListBuffer | |
| import scala.collection.mutable.StringBuilder | |
| object Main { | |
| def main(args: Array[String]) { | |
| try { | |
| println(searchLongestSubsequence("")) | |
| } catch { | |
| case e: Exception => println(e.toString()) // "Empty String" | |
| } | |
| println(searchLongestSubsequence("010")) // 01 | |
| println(searchLongestSubsequence("1123")) // 123 | |
| println(searchLongestSubsequence("122345")) // 2345 | |
| println(searchLongestSubsequence("987123")) // 123 | |
| println(searchLongestSubsequence("97463288890")) // 46 | |
| println(searchLongestSubsequence("83625469835377789")) // 469 | |
| } | |
| def searchLongestSubsequence(str: String) = { | |
| def splitIncreasingSubsequence(str: String): List[String] = { | |
| val subseqs = new ListBuffer[String] | |
| val subseq = new ListBuffer[Char] | |
| def split(chars: List[Char]) { | |
| chars match { | |
| case hd :: Nil => { | |
| subseq += hd | |
| subseqs += subseq.mkString | |
| } | |
| case hd :: tl if (hd < tl.head) => { | |
| subseq += hd | |
| split(tl) | |
| } | |
| case hd :: tl if (hd >= tl.head) => { | |
| subseq += hd | |
| subseqs += subseq.mkString | |
| subseq.clear() | |
| split(tl) | |
| } | |
| } | |
| } | |
| split(str.toList) | |
| subseqs.toList | |
| } | |
| str match { | |
| case "" => throw new IllegalArgumentException("Empty String.") | |
| case xs => splitIncreasingSubsequence(xs).maxBy(_.length) | |
| } | |
| } | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment