Skip to content

Instantly share code, notes, and snippets.

@jsaund
Last active October 15, 2015 04:49
Show Gist options
  • Save jsaund/c15cf7c5df0cf6842617 to your computer and use it in GitHub Desktop.
Save jsaund/c15cf7c5df0cf6842617 to your computer and use it in GitHub Desktop.
A collection of string operations using Scala's functional principles.
object Strings {
def isAnagram(s1: String, s2: String): Boolean = {
if (s1 == null || s2 == null || s1.length != s2.length) return false
s1.zip(s2).foldLeft(0){ case (result, (left, right)) => result ^ (left ^ right) } == 0
}
def isAnagram2(s1: String, s2: String): Boolean = {
val m1 = s1 groupBy(c => c) mapValues(_.length)
val m2 = s2 groupBy(c => c) mapValues(_.length)
(m1 ++ m2).map{ case (k,v) => v - m1.getOrElse(k, 0) }.sum == 0
}
def isParenthesisBalanced(s: String): Boolean = {
val openParens = Set('(', '[', '{')
val closeParens = Set(')', ']', '}')
val m = closeParens.zip(openParens).toMap
s.toCharArray.foldLeft(List[Char]()){
case (rs, open) if openParens.contains(open) => open :: rs
case (r :: rs, closed) if closeParens.contains(closed) && m.get(closed).get == r => rs
case (rs, closed) if closeParens.contains(closed) => 'x' :: rs
case (rs, _) => rs
}.isEmpty
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment