方法一:排序
思路:说实话如果不是我看了这道题的分类属于排序分组里,还真的挺难的。
static void Main(string[] args)
{
string a = "rat";
string b = "car";
bool res = GetYW(a,b);
Console.Write(res);
Console.ReadKey();
}
private static bool GetYW(string a, string b)
{
bool res = true;
char[] t1 =a.ToCharArray();
char[] t2 = b.ToCharArray();
Array.Sort(t1);
Array.Sort(t2);
return ch1.SequenceEqual(ch2);
}
知识点:array.sort() . 排序
SequenceEqual : 确定两个序列是否相等的元素进行比较通过使用相应类型的默认相等比较器。
方法二: 计算总数
private static bool isAnagram(string s, string t)
{
if (s.Length != t.Length)
return false;
int[] counts = new int[26];
for (int i = 0; i < s.Length; i++)
{
counts[s[i] - 'a']++;
counts[t[i] - 'a']--;
}
foreach (var count in counts)
{
if (count!=0)
{
return false;
}
}
return true;
}
方法三: 哈希
public bool IsAnagram(string s, string t) {
if (s.Length != t.Length)
return false;
Dictionary<char, int> dict = new Dictionary<char, int>();
for (int i = 0; i < s.Length; i++)
{
if(!dict.ContainsKey(s[i]))
dict.Add(s[i], 1);
else
dict[s[i]]++;
}
for (int j = 0; j < t.Length; j++)
{
if (!dict.ContainsKey(t[j]) || --dict[t[j]] < 0) // --dict[t[j]] < 0 用于判断从头扫描到尾,t中有没有出现次数多于s中的字符
return false;
}
return true;
}