LeetCode-242.Valid Anagram
Given two strings s and t , write a function to determine if t is an anagram of s.
Example 1:
Input: s = "anagram", t = "nagaram" Output: true
Example 2:
Input: s = "rat", t = "car" Output: false
Note:
You may assume the string contains only lowercase alphabets.
Follow up:
What if the inputs contain unicode characters? How would you adapt your solution to such case?
使用map,时间复杂度O(n)
public boolean isAnagram(String s, String t) {//map my if(null==s&&null==t){ return true; } if(null==s||null==t||s.length()!=t.length()){ return false; } Map<Character,Integer> map = new HashMap<>(); for (int i = 0; i < s.length(); i++) { char c= s.charAt(i); if(map.containsKey(c)){ map.put(c,map.get(c)+1); } else{ map.put(c,1); } } for (int i = 0; i < t.length(); i++) { char c= t.charAt(i); if(map.containsKey(c)){ map.put(c,map.get(c)-1); if(map.get(c)==0){ map.remove(c); } } else{ return false; } } return true; }
上面的方法具有普遍性,针对该题可以使用数组解决,因为只有26个小写字母,时间复杂度也是O(n)。
还可以使用排序的方法,但时间复杂度是O(nlogn)。
进阶题
异位词分组 LeetCode49 https://www.cnblogs.com/zhacai/p/10576638.html
查找所有异位词 LeetCode438 https://www.cnblogs.com/zhacai/p/10596274.html