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
Copy the code

Example 2:

Input: s = "rat", t = "car"
Output: false
Copy the code

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?

Solution a:

Use two maps to record the number of occurrences of each character and compare them.

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
    }
}
Copy the code

Method 2:

Sort the two strings and compare them.

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
    }
}
Copy the code

Method 3:

We first determine if the two strings are of the same length and return false if they are not. Then count up all the characters in s and store them in an array of size 26, because the problem limited the input string to lowercase letters. We then count the T string and return false if we find a mismatch. See the code below:

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}}Copy the code