Valid Anagram 解答

时间:2023-03-08 18:00:44

Question

Given two strings s and t, write a function to determine if t is an anagram of s.

For example,
s = "anagram", t = "nagaram", return true.
s = "rat", t = "car", return false.

(An anagram is a type of word play, the result of rearranging the letters of a word or phrase to produce a new word or phrase, using all the original letters exactly once; for example Torchwood can be rearranged into Doctor Who.)

Solution

Use hashmap to count each character's appearance time. Time complexity O(n), space cost O(n).

Note here, counts.put(tmp, count.get(tmp)--); is wrong!

 public class Solution {
public boolean isAnagram(String s, String t) {
if (s == null || t == null)
return false;
if (s.length() != t.length())
return false;
Map<Character, Integer> counts = new HashMap<Character, Integer>();
int length = s.length();
for (int i = 0; i < length; i++) {
char tmp = s.charAt(i);
if (counts.containsKey(tmp)) {
int count = (int)counts.get(tmp);
counts.put(tmp, count + 1);
} else {
counts.put(tmp, 1);
}
}
for (int i = 0; i < length; i++) {
char tmp = t.charAt(i);
if (counts.containsKey(tmp)) {
int count = (int)counts.get(tmp);
if (count <= 0)
return false;
else
counts.put(tmp, count - 1);
} else {
return false;
}
}
return true;
}
}

++x is called preincrement while x++ is called postincrement.

 int x = 5, y = 5;

 System.out.println(++x); // outputs 6
System.out.println(x); // outputs 6 System.out.println(y++); // outputs 5
System.out.println(y); // outputs 6