242.242-Valid Anagram-Difficulty: Easy
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.
思路
查找t的字母是否全和s相同(数目也相同)
使用哈希表匹配轻松解决
要注意重复情况,在哈希的value几下当前字母个数,t遇到就-1,到0还有的话就是false了
public class Solution {
public bool IsAnagram(string s, string t) {
if (s.Length != t.Length)
return false;
Hashtable hash = new Hashtable();
for (int i = 0; i < s.Length; i++)
{
if (hash.ContainsKey(s[i]))
hash[s[i]] = (int)hash[s[i]] + 1;
else
hash.Add(s[i], 1);
}
for (int i = 0; i < s.Length; i++)
{
if (hash.ContainsKey(t[i]))
{
if ((int)hash[t[i]] <= 0)
return false;
hash[t[i]] = (int)hash[t[i]] - 1;
}
else
return false;
}
return true;
}
}