This is the 13th day of my participation in the August More Text Challenge. For details, see:August is more challenging

Topic Description:

242. Valid Ectopes – LeetCode (leetcode-cn.com)

Given two strings, s and t, write a function to determine whether t is a letter ectopic of S.

Note: if each character in s and T occurs the same number of times, s and t are said to be alphabetic ectopes.

The sample a

Input: s = "anagram", t = "nagaram" Output: trueCopy the code

Example 2

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

Tip:


  • 1 < = s . l e n g t h . t . l e n g t h < = 5 1 0 4 1 <= s.length, t.length <= 5 * 10^4
  • stContains only lowercase letters

 

Advanced: What if the input string contains Unicode characters? Can you adjust your solution to this situation?

Thought analysis

The sorting

If two strings are ectopes, they contain the same number of letters, but in a different order. So we just put the strings into an array and sort them

AC code

class Solution {
    fun isAnagram(originString: String, destString: String): Boolean {
        if(originString.length ! = destString.length)return false

        val originCharArray = originString.toCharArray()
        val destCharArray = destString.toCharArray()
        
        originCharArray.sort()
        destCharArray.sort()
        return originCharArray.contentEquals(destCharArray)
    }
}
Copy the code

Hash table

There are several ways to solve the problem using a hash table. For a simple one, we know that if two strings are ectopes, they contain the same number of letters, so we just need to count the number of each letter in the string and store it in a hash table, and then compare the two hash tables

AC code

class Solution {
    fun isAnagram(s: String, t: String): Boolean {
     var m1 = mutableMapOf<Char.Int> ()var m2 = mutableMapOf<Char.Int>()
     
     s.toCharArray().forEach{
         varvalue=m1[it]? :0
         m1[it] = ++value 
     }
     
     t.toCharArray().forEach{
         varvalue=m2[it]? :0
         m2[it] = ++value 
     }
     return m1==m2
    }
}
Copy the code

This is the case of two maintaining two hash tables, you can also maintain a hash table, the first one to add, the second one to subtract, if it is an ectopic word, then the last hash table must be empty ~, this is also easy, I won’t paste the code.

conclusion

This problem is still relatively simple, once AC, but this problem has an advanced problem, need to understand Unicode related encoding problems, this solution wait for me to study next to complement.

reference

Valid Ectopes – Valid Ectopes – LeetCode (leetcode-cn.com)

242. Valid Ectopes – Valid Ectopes – LeetCode (leetcode-cn.com)