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?
解释:首先简单介绍一下Anagram(回文构词法)。Anagrams是指由颠倒字母顺序组成的单词,比如“dormitory”颠倒字母顺序会变成“dirty room”,“tea”会变成“eat”。回文构词法有一个特点:单词里的字母的种类和数目没有改变,只是改变了字母的排列顺序。
方法一:哈希表
class Solution { public boolean isAnagram(String s, String t) { if(s.toCharArray().length!=t.toCharArray().length) return false; HashMap<Character,Integer> map=new HashMap<Character,Integer>(); for(char c:s.toCharArray()){ if(map.containsKey(c)){ int nums=map.get(c); map.put(c,nums+1); }else{ map.put(c,1); } } for(char c:t.toCharArray()){ if(!map.containsKey(c)){ return false; } int nums=map.get(c); if(nums==1){ map.remove(c); }else{ nums--; map.put(c,nums); } } return true; } }
方法二:快排
先对每个数组排序,再比较是否一样。
class Solution { public boolean isAnagram(String s, String t) { if(s.toCharArray().length!=t.toCharArray().length) return false; char[] cs=s.toCharArray(); char[] ct=t.toCharArray(); quickSort(cs,0,cs.length-1); quickSort(ct,0,ct.length-1); for(int i=0;i<cs.length;i++){ if(cs[i]!=ct[i]) return false; } return true; } private void quickSort(char[] array,int low,int high){ int i,j; char t,temp; if(low>high) return ; i=low; j=high; temp=array[low]; while(i<j){ while(temp<=array[j]&&i<j) j--; while(temp>=array[i]&&i<j) i++; if(i<j){ t=array[i]; array[i]=array[j]; array[j]=t; } } array[low]=array[j]; array[j]=temp; quickSort(array,low,j-1); quickSort(array,j+1,high); } }
苟有恒,何必三更眠五更起;最无益,莫过一日暴十日寒。