-
Notifications
You must be signed in to change notification settings - Fork 141
Expand file tree
/
Copy pathQ1_02_Check_Permutation.cs
More file actions
74 lines (63 loc) · 2.17 KB
/
Copy pathQ1_02_Check_Permutation.cs
File metadata and controls
74 lines (63 loc) · 2.17 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
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
using ctci.Contracts;
using System;
using System.Collections.Generic;
using System.Linq;
namespace Chapter01
{
public class Q1_02_Check_Permutation : Question
{
private bool IsPermutation(string original, string valueToTest)
{
if (original.Length != valueToTest.Length)
return false;
var originalAsArray = original.ToCharArray();
Array.Sort(originalAsArray);
var valueToTestAsArray = valueToTest.ToCharArray();
Array.Sort(valueToTestAsArray);
return originalAsArray.SequenceEqual(valueToTestAsArray);
}
private bool IsPermutation2(string original, string valueToTest)
{
if (original.Length != valueToTest.Length)
return false;
var letterCount = new Dictionary<char, int>();
foreach (var character in original)
{
if (letterCount.ContainsKey(character))
letterCount[character]++;
else
letterCount[character] = 1;
}
foreach (var character in valueToTest)
{
if (letterCount.ContainsKey(character))
{
letterCount[character]--;
if (letterCount[character] < 0)
{
return false;
}
}
else return false;
}
return true;
}
public override void Run()
{
string[][] pairs =
{
new string[]{"apple", "papel"},
new string[]{"carrot", "tarroc"},
new string[]{"hello", "llloh"}
};
foreach (var pair in pairs)
{
var word1 = pair[0];
var word2 = pair[1];
var result1 = IsPermutation(word1, word2);
var result2 = IsPermutation2(word1, word2);
Console.WriteLine("{0}, {1}: {2} / {3}", word1, word2, result1, result2);
}
}
}
}