Tuesday, December 1, 2015

[leetcode] Valid Anagram

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
public class Solution {
    public boolean isAnagram(String s, String t) {
     if (s.length() != t.length()) return false;
   HashMap<Character, Integer> lookup = new HashMap<Character, Integer>();
   for (int i = 0; i < s.length(); i++){
    int count = 1;
    char current = s.charAt(i);
    if (lookup.containsKey(current)){
     count = lookup.get(current)+1;
    }
    lookup.put(current, count);
   }
   for (int i = 0; i < t.length(); i++){
    char current = t.charAt(i);
    if (!lookup.containsKey(current)) return false;
    int count = lookup.get(current)-1;
    if (count == 0) lookup.remove(current);
    else lookup.put(current, count);
   }

   return lookup.size()==0;
    }
}

No comments:

Post a Comment