-
Notifications
You must be signed in to change notification settings - Fork 3
/
ReverseString.cs
115 lines (93 loc) · 3.25 KB
/
ReverseString.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
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
using System.Text;
using System.Linq;
using BenchmarkDotNet.Attributes;
namespace Algorithms.ArraysAndStrings
{
[MemoryDiagnoser]
public class ReverseString
{
private const string INPUT = "Learning Algorithms";
//Time: O(n)
//Space: O(n)
[Benchmark(Baseline = true)]
[Arguments(INPUT)]
public string FirstTry(string myEntireString)
{
StringBuilder reversedString = new StringBuilder(myEntireString.Length);
for (int i = myEntireString.Length - 1; i >= 0; i--)
reversedString.Append(myEntireString[i]);
return reversedString.ToString();
}
//Time: O(n)
//Space: O(n)
[Benchmark]
[Arguments(INPUT)]
public string InJustOneLine(string myEntireString)
{
return string.Join("", myEntireString.ToCharArray().Reverse());
}
//Time: O(n)
//Space: O(n)
[Benchmark]
[Arguments(INPUT)]
public string InJustOneLine2(string myEntireString)
{
return new string(myEntireString.Reverse().ToArray());
}
//Time: O(n/2)
//Space: O(n)
[Benchmark]
[Arguments(INPUT)]
public string Fast(string myEntireString)
{
int halfSize = myEntireString.Length / 2;
char[] reversedArray = new char[myEntireString.Length];
for (int i = 0; i < halfSize; i++)
{
reversedArray[i] = myEntireString[myEntireString.Length - 1 - i];
reversedArray[reversedArray.Length - 1 - i] = myEntireString[i];
}
if (halfSize % 2 != 0)
reversedArray[halfSize] = myEntireString[halfSize];
return new string(reversedArray);
}
[Benchmark]
[Arguments(INPUT)]
public string Vafzamora_Fast1(string myEntireString)
{
char[] reversedArray = myEntireString.ToCharArray();
char buffer = ' ';
for (int i = 0, j = myEntireString.Length - 1; i < myEntireString.Length / 2; i++, j--)
{
buffer = reversedArray[i];
reversedArray[i] = reversedArray[j];
reversedArray[j] = buffer;
}
return new string(reversedArray);
}
[Benchmark]
[Arguments(INPUT)]
public string Vafzamora_Fast2(string myEntireString)
{
char[] reversedArray = new char[myEntireString.Length];
int middle = (myEntireString.Length / 2 + myEntireString.Length % 2);
for (int i = 0, j = myEntireString.Length - 1; i < middle; i++, j--)
{
reversedArray[i] = myEntireString[j];
reversedArray[j] = myEntireString[i];
}
return new string(reversedArray);
}
[Benchmark]
[Arguments(INPUT)]
public string Vafzamora_Obvious(string myEntireString)
{
char[] reversedArray = new char[myEntireString.Length];
for (int i = myEntireString.Length - 1, j = 0; i >= 0; i--, j++)
{
reversedArray[j] = myEntireString[i];
}
return new string(reversedArray);
}
}
}