“This is the 10th day of my participation in the Gwen Challenge in November. Check out the details: The Last Gwen Challenge in 2021.”
[B] [C] [D]
Given two strings s and t, write a function to determine whether t is an alphabetic allotopic of S.
Note: s and T ** are said to be alphabetic allographs if each character appears the same number of times.
Example 1:
Input: s = "anagram", t = "nagaram" Output: trueCopy the code
Example 2:
Input: s = "rat", t = "car" output: falseCopy the code
Tip:
1 <= s.length, t.length <= 5 * 104
s
和t
Contains only lowercase letters
The solution is as follows:
If two strings are alphabetic, they have the same character structure, but the positions of the characters may be different
First, determine whether the two strings are equal in length. If they are not, they are definitely not alphabetic
The map then records the occurrence of characters in each string and the number of occurrences
The map of one character is traversed to check whether the map of the other character has the same key and the corresponding value val is the same. If the key is not the same, it indicates that the key is not an allotopic word
If so, delete the key from both maps
Finally, check whether the map corresponding to the two strings is empty
The code is as follows:
var isAnagram = function(s, t) { const lens = s.length, lent = t.length; If (lens! == lent) return false; Const maps = new map (), mapt = new map (); for(let i = 0; i<lens; i++){ let cur = s[i] if(maps.has(cur)){ maps.set(cur,maps.get(cur)+1) }else{ maps.set(cur,1) } cur = t[i] If (mapt.has(cur)){mapt.set(cur,mapt.get(cur)+1)}else{mapt.set(cur,1)}} if(mapt.get(item[0])! == item[1]) return false; Maps.delete (item[0]) mapt.delete(item[0])} return maps.size===0 && mapt.size===0}; return maps.size===0 && mapt.size===0}; return maps.size== 0 && mapt.size===0};Copy the code
At this point we have leetcode-242- a valid letter heterotopic word
If you have any questions or suggestions, please leave a comment!