Created
April 10, 2020 04:42
-
-
Save danwang/db105a37cfc3ac18db051afe427cc5d9 to your computer and use it in GitHub Desktop.
BackspaceStringCompare.scala
This file contains 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
object Solution { | |
def backspaceCompare(left: String, right: String): Boolean = { | |
case class State(string: String, pointer: Int, backspaces: Int) { | |
def charOption: Option[Char] = { | |
if (pointer < 0 || pointer >= string.length) { | |
None | |
} else { | |
Some(string.charAt(pointer)) | |
} | |
} | |
def finalLetter: Option[Char] = { | |
charOption match { | |
case Some('#') => None | |
case Some(_) if backspaces == 0 => charOption | |
case _ => None | |
} | |
} | |
def next: State = { | |
charOption match { | |
case Some('#') => State(string, pointer - 1, backspaces + 1) | |
case Some(_) => State(string, pointer - 1, Math.max(backspaces - 1, 0)) | |
case None => State(string, pointer, backspaces) | |
} | |
} | |
} | |
def helper(left: State, right: State): Boolean = { | |
(left.charOption, right.charOption) match { | |
// Reached beginning of both strings | |
case (None, None) => true | |
// Reached beginning of one string, but not the other. There should | |
// be no more final letters in the other one | |
case (Some(_), None) => left.finalLetter.isEmpty && helper(left.next, right) | |
case (None, Some(_)) => right.finalLetter.isEmpty && helper(left, right.next) | |
case (Some(_), Some(_)) => { | |
(left.finalLetter, right.finalLetter) match { | |
case (None, None) => helper(left.next, right.next) | |
case (Some(_), None) => helper(left, right.next) | |
case (None, Some(_)) => helper(left.next, right) | |
// Two final letters -- they should match | |
case (Some(l), Some(r)) => l == r && helper(left.next, right.next) | |
} | |
} | |
} | |
} | |
helper(State(left, left.length - 1, 0), State(right, right.length - 1, 0)) | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment