0
\$\begingroup\$

The problem is: Given two strings, write a method to decide if one is a permutation of the other. I wrote the following code in scala, may I know any other optimization one?

def checkpermutation(str1:String, str2:String): Boolean=(str1, str2) match {
 case (a,b) if a==b => true
 case (a,b) if a.length() !=b.length() =>false
 case (a,b) if a.toList.sorted.mkString== a.toList.sorted.mkString => true
 case _ =>false
 }
asked Nov 30, 2016 at 10:24
\$\endgroup\$
1
  • \$\begingroup\$ The third case is invalid: it checks a.toList.sorted.mkString with itself. \$\endgroup\$ Commented Nov 30, 2016 at 12:43

1 Answer 1

2
\$\begingroup\$

There is no need to use matchers for this check. A logical expression would be enough:

def checkpermutation2(a:String, b:String): Boolean = {
 def sorted(s: String) = s.sorted.mkString
 (a == b) || (a.length == b.length && sorted(a) == sorted(b))
} 
answered Nov 30, 2016 at 12:49
\$\endgroup\$

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.