likes
comments
collection
share

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

作者站长头像
站长
· 阅读数 1

leetcode.com/problems/va…

Discuss:www.cnblogs.com/grandyang/p…

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
    }
}

解法三:

我们先判断两个字符串长度是否相同,不相同直接返回false。然后把s中所有的字符出现个数统计起来,存入一个大小为26的数组中,因为题目中限定了输入字符串为小写字母组成。然后我们再来统计t字符串,如果发现不匹配则返回false。 参见代码如下:

class Solution {
    fun isAnagram(s: String, t: String): Boolean {
        if (s.length != t.length) {
            return false
        }

        val array: IntArray = IntArray(26) { 0 }
        s.withIndex().forEach {
            array[it.value - 'a']++
        }

        t.withIndex().forEach {
            if (--array[it.value - 'a'] < 0) {
                return false
            }
        }
        return true
    }
}