leetcode刷题笔记 242题 有效的字母异位词

leetcode刷题笔记 242题 有效的字母异位词

源地址:242. 有效的字母异位词

问题描述:

给定两个字符串 s 和 t ,编写一个函数来判断 t 是否是 s 的字母异位词。

示例 1:

输入: s = "anagram", t = "nagaram"
输出: true
示例 2:

输入: s = "rat", t = "car"
输出: false
说明:
你可以假设字符串只包含小写字母。

进阶:
如果输入字符串包含 unicode 字符怎么办?你能否调整你的解法来应对这种情况?

//使用哈希表记录字符串的构成,比较两个哈希表的内容是否一致
import scala.collection.mutable
object Solution {
    def isAnagram(s: String, t: String): Boolean = {
        if (s.size != t.size) return false
        val mapS = mutable.Map[Char, Int]()
        val mapT = mutable.Map[Char, Int]()
        
        s.foreach(c => mapS.put(c, mapS.getOrElse(c, 0) + 1))
        t.foreach(c => mapT.put(c, mapT.getOrElse(c, 0) + 1))
        
        return mapS == mapT
    }
}

//使用算子 思路一致
import scala.collection.mutable
object Solution {
    def isAnagram(s: String, t: String): Boolean = s.groupBy(identity).mapValues(_.length).toMap == t.groupBy(identity).mapValues(_.length).toMap
}
原文地址:https://www.cnblogs.com/ganshuoos/p/13900803.html