LeetCode 242. Valid Anagram(有效的字母异位词)

leetcode.com/problems/va…

Given two strings s and t, return true if t is an anagram of s, and false otherwise.

Example 1:

Input: s = "anagram", t = "nagaram"
Output: true
复制代码

Example 2:

Input: s = "rat", t = "car"
Output: false
复制代码

Constraints:

  • 1 <= s.length, t.length <= 5 * 104

  • s and t consist of lowercase English letters.

Follow up: What if the inputs contain Unicode characters? How would you adapt your solution to such a case?

解法一:

使用两个 Map 记录每个字符出现的次数,然后比较。

class Solution {
    fun isAnagram(s: String, t: String): Boolean {
        val sMap = mutableMapOf<Char, Int>()
        val tMap = mutableMapOf<Char, Int>()

        s.forEach {
            sMap[it] = (sMap[it] ?: 0) + 1
        }

        t.forEach {
            tMap[it] = (tMap[it] ?: 0) + 1
        }

        return sMap == tMap
    }
}
复制代码

解法二:

对两个字符串进行排序,然后比较。

class Solution {
    fun isAnagram(s: String, t: String): Boolean {
        var sList = s.toList()
        var tList = t.toList()
        
        sList = sList.sorted()
        tList = tList.sorted()

        return sList==tList
    }
}
复制代码
© 版权声明
THE END
喜欢就支持一下吧
点赞0 分享