242. Valid Anagram

题目:

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.

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?

链接: http://leetcode.com/problems/valid-anagram/

3/2/2017

写法比较弱,有几行有改动,比如最后不需要检查hashmap是否为空,因为如果长度相同的话,中间必定会有某个字符多而另一字符少的情况,结果在前面就可以返回了。

同理当hashmap里剩余count为0时再碰到相同字符也是错误的,不需要remove

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

还可以用bitmap,留给二刷

原文地址:https://www.cnblogs.com/panini/p/6493805.html