Valid Anagram 解答

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!

 

 1 public class Solution {
 2     public boolean isAnagram(String s, String t) {
 3         if (s == null || t == null)
 4             return false;
 5         if (s.length() != t.length())
 6             return false;
 7         Map<Character, Integer> counts = new HashMap<Character, Integer>();
 8         int length = s.length();
 9         for (int i = 0; i < length; i++) {
10             char tmp = s.charAt(i);
11             if (counts.containsKey(tmp)) {
12                 int count = (int)counts.get(tmp);
13                 counts.put(tmp, count + 1);
14             } else {
15                 counts.put(tmp, 1);
16             }
17         }
18         for (int i = 0; i < length; i++) {
19             char tmp = t.charAt(i);
20             if (counts.containsKey(tmp)) {
21                 int count = (int)counts.get(tmp);
22                 if (count <= 0)
23                     return false;
24                 else
25                     counts.put(tmp, count - 1);
26             } else {
27                 return false;
28             }
29         }
30         return true;
31     }
32 }

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

1 int x = 5, y = 5;
2 
3 System.out.println(++x); // outputs 6
4 System.out.println(x); // outputs 6
5 
6 System.out.println(y++); // outputs 5
7 System.out.println(y); // outputs 6

 

posted @ 2015-09-15 02:04  树獭君  阅读(164)  评论(0编辑  收藏  举报