1 Example 1 : 2 . 3 Input: S = " Anagram " , T = " nagaram " . 4 Output: to true . 5 Example 2 : . 6 . 7 Input: S = " RAT " , T = " CAR " . 8 Output: false
Note: You can assume that the string contains only lowercase letters.
Advanced: If the input string contains character how to do? Can you adjust your solution to deal with this situation? unicode
Let's look at the god of the following operations:
First talk about the use of sorted / sort of:
Basic sorting, calling sorted () function to back a new sorted list, if you do not need the original list can also use list.sort () to achieve, he directly modify the original list, efficiency () higher than sorted.
1 sorted([5, 2, 3, 1, 4]) #[1, 2, 3, 4, 5] 2 a = [5, 2, 3, 1, 4] #a.sort() [1, 2, 3, 4, 5]
Another difference is that the method is only defined as a list, and the function can accept any iterables.list.sort()
sorted()
1 sorted({1: 'D', 2: 'B', 3: 'B', 4: 'E', 5: 'A'}) #[1, 2, 3, 4, 5]
Problem solution 1:
Generating an anagram by rearranging letters s t. Thus, if T is S, anagram, two strings of the sort produces two identical strings. In addition, if the length of t s and t can not be a different anagram s, we can return in advance.
1 #排序 2 class Solution(object): 3 def isAnagram(self, s, t): 4 """ 5 :type s: str 6 :type t: str 7 :rtype: bool 8 """ 9 if len(s) != len(t): 10 return False 11 if sorted(s) != sorted(t): 12 return False 13 return True
Problem solution 2:
-
In order to check whether the rearranged s t, we can calculate the number of occurrences of each two letter strings and compared. Because S and T contains only the letters A-Z, so that a simple 26-bit counter table is sufficient.
-
We need you to compare two counters that table? Not actually, since the frequency of the letters s we can calculate with a counter table, a table counter t to reduce each letter of the counter, and then check whether the counter back to zero.
1 # Hash 2 # standard dictionary includes setdefault method () Gets a value, if the value does not exist, the establishment of a default. In contrast, defaultdict allows the caller to a pre-set default values upon initialization. . 3 class Solution (Object): . 4 DEF isAnagram (Self, S, T): . 5 "" " . 6 : type S: STR . 7 : type T: STR . 8 : rtype: BOOL . 9 " "" 10 IF len (S)! = len (T): . 11 return False 12 is dicts = collections.defaultdict (int) 13 is for I in Range (len (S)): 14 dicts[s[i]] = dicts[s[i]] + 1 15 dicts[t[i]] = dicts[t[i]] - 1 16 for val in dicts.values(): 17 if val != 0: 18 return False 19 return True
beginner
Share and success, your nemesis is me, remember that the quality of triple!
Source: stay button (LeetCode) link: https://leetcode-cn.com/problems/valid-anagram