Question
Write a method anagram(s,t) to decide if two strings are anagrams or not.
Example
Given s = "abcd" , t = "dcab" , return true .
Given s = "ab" , t = "ab" , return true .
Given s = "ab" , t = "ac" , return false .
Clarification
What is Anagram?
- Two strings are anagram if they can be the same after change the order of characters.
Thinking
- Using map to store the count of each character.
- Character in first string is adding while character in second string is substrcting.
- Every character count must be 0 in the map.
Solution
Java
public class Solution {
/**
* @param s: The first string
* @param b: The second string
* @return true or false
*/
public boolean anagram(String s, String t) {
// write your code here
if (s == null && t == null) {
return true;
}
if ((s == null && t != null) || (s != null && t == null)) {
return false;
}
if (s.length() != t.length()) {
return false;
}
Map<Character, Integer> countMap = new HashMap<Character, Integer>();
for (int i = 0; i < s.length(); i++) {
char skey = s.charAt(i);
char tkey = t.charAt(i);
if (countMap.get(skey) == null) {
countMap.put(skey, 1);
} else {
countMap.put(skey, (countMap.get(skey) + 1));
}
if (countMap.get(tkey) == null) {
countMap.put(tkey, -1);
} else {
countMap.put(tkey, (countMap.get(tkey) - 1));
}
}
Set<Character> keys = countMap.keySet();
for (Character key : keys) {
if (countMap.get(key) != 0) {
return false;
}
}
return true;
}
};