-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy path0242-Valid-anagram.cs
More file actions
54 lines (44 loc) · 1.27 KB
/
0242-Valid-anagram.cs
File metadata and controls
54 lines (44 loc) · 1.27 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
using System;
using System.Collections.Generic;
using System.Text;
namespace Solution._0242.Valid_anagram
{
public class _0242_Valid_anagram
{
public bool IsAnagram(string s, string t)
{
// Solution 1
//if (s.Length != t.Length)
// return false;
//char[] ch1 = s.ToCharArray();
//char[] ch2 = t.ToCharArray();
//Array.Sort(ch1);
//Array.Sort(ch2);
//for (int i = 0; i < ch1.Length; i++)
// if (ch1[i] != ch2[i])
// return false;
//return true;
// Solution 2
if (s.Length != t.Length) return false;
Dictionary<int, int> dic = new Dictionary<int, int>();
foreach (char c in s)
{
if (dic.ContainsKey(c))
dic[c] += 1;
else
dic.Add(c, 1);
}
foreach (char c in t)
{
if (dic.ContainsKey(c))
{
if (dic[c] == 1)
dic.Remove(c);
else dic[c] -= 1;
}
else return false;
}
return dic.Count == 0;
}
}
}