242. Valid Anagram
[242. Valid Anagram](https://leetcode.com/problems/valid-anagram/)
判断字符是否是重排字符
Solution 1 str转array-排序array后比较
思路:string转char array,对char array进行排序;再比较两个数组是否相等即可。
Runtime: 2 ms, faster than 94.75% of Java online submissions for Valid Anagram.
Memory Usage: 39.4 MB, less than 40.34% of Java online submissions for Valid Anagram.
1 | class Solution { |
Solution 2 str转array-map统计字符出现次数
思路:string转char array,对char array中出现的字符及其次数进行统计,再比较。
Runtime: 11 ms, faster than 23.84% of Java online submissions for Valid Anagram.
Memory Usage: 39.6 MB, less than 28.85% of Java online submissions for Valid Anagram.
效率可谓是极差, 但是思路比较简单
1 | class Solution { |
Solution3 best one–str转array,再用数组统计次数
思路:解法类似于boomfilter判断一个数是否存在过一样。字母只有26位,初始化一个26位的数组,然后将其ascii码减去‘a’的ascii码,计算出在数组中的位置,然后执行+1操作
另一个数组,同上,但是执行-1操作。如果两字符串相同,则数组最终为26个0。
Runtime: 1 ms, faster than 100.00% of Java online submissions for Valid Anagram.
Memory Usage: 38.9 MB, less than 96.44% of Java online submissions for Valid Anagram.
Time Complexity: O(n)
Space Complexity: O(1)
1 | class Solution { |