/
TwoStringAreAnagramStrings.cs
89 lines (76 loc) · 2.56 KB
/
TwoStringAreAnagramStrings.cs
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
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
using System;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace TwoStringAreAnagramStrings
{
class TwoStringAreAnagramStrings
{
Hashtable collection = new Hashtable();
public static class testCases
{
public static string[] test = {"test","tset"};
public static string[] testFail = { "test", "ts1et" };
}
static void Main(string[] args)
{
bool value = isAnagram(TwoStringAreAnagramStrings.testCases.test);
bool failValue = isAnagram(TwoStringAreAnagramStrings.testCases.testFail);
System.Console.WriteLine("result is " + value.ToString());
}
public static bool isAnagram(string[] test)
{
Hashtable tmp = new Hashtable();
int count = 0;
foreach (string s in test)
{
if (count == 0)
{
foreach (char c in s)
{
string key = c.ToString();
if (tmp.Contains(key))
{
int value = (int)tmp[key];
tmp[key] = value + 1;
}
else
{
tmp.Add(key, 1);
}
}
}
if (count == 1)
{
foreach (char c in s)
{
string key = c.ToString();
if (!tmp.Contains(key)) return false;
else
{
int value = (int)tmp[key];
if (value - 1 < 0) return false;
tmp[key] = value - 1;
}
}
// at the end, check tmp each value ==0
foreach (DictionaryEntry entry in tmp)
{
int value = (int)entry.Value;
if (value > 0) return false;
// redundant check
if (value < 0)
{
return false; // unreachable code
}
}
return true;
}
count++;
}
return false;
}
}
}