Checking if 2 strings contain the same characters?

前端 未结 10 948
孤城傲影
孤城傲影 2020-12-10 04:49

Is there a way to check if two strings contain the same characters. For example,

abc, bca -> true
aaa, aaa -> true
aab, bba -> false
abc, def ->          


        
10条回答
  •  情深已故
    2020-12-10 05:14

    Agree to what @Jean says above for an efficient solution using HashMap. This problem is also called Anagram. Below is the solution in Scala.

    Note: cleanString is where whitespaces are removed and all characters are lowercase

    def isAnagram(cleanString1, cleanString2) = {
      createHashMap(cleanString1) == createHashMap(cleanString2)
    }
    
    def createHashMap(str: String): immutable.HashMap[Char, Int] = {
      str.foldLeft(immutable.HashMap.empty[Char, Int]) { (acc, next)
      => if (acc.contains(next)) acc + (next -> (acc(next) + 1)) 
         else acc + (next -> 1)
         }
    }
    

提交回复
热议问题