标签:amp log 解决 alpha min nlog determine case ash
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)。
标签:amp log 解决 alpha min nlog determine case ash
原文地址:https://www.cnblogs.com/zhacai/p/10574647.html