Repository navigation
Expand file tree
/
Copy pathSimpleTextEditor.cs
More file actions
55 lines (49 loc) · 1.78 KB
/
Copy pathSimpleTextEditor.cs
File metadata and controls
55 lines (49 loc) · 1.78 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
using System.Text;
namespace HackerRank.Solutions.DataStructures;
/// <summary>
/// Simple Text Editor — support "1 W" (append), "2 k" (delete last k), "3 k" (print k-th
/// character) and "4" (undo the last append or delete). Each edit pushes its inverse onto an
/// undo stack, so no full snapshots of the text are kept. Returns the printed characters.
/// https://www.hackerrank.com/challenges/simple-text-editor
/// </summary>
public static class SimpleTextEditor
{
public static string[] Solve(IReadOnlyList<string> operations)
{
var text = new StringBuilder();
var undo = new Stack<(bool WasAppend, string Payload)>();
var printed = new List<string>();
foreach (var operation in operations)
{
var parts = operation.Split(' ', 2);
switch (parts[0])
{
case "1":
text.Append(parts[1]);
undo.Push((true, parts[1]));
break;
case "2":
int count = int.Parse(parts[1]);
string removed = text.ToString(text.Length - count, count);
text.Length -= count;
undo.Push((false, removed));
break;
case "3":
printed.Add(text[int.Parse(parts[1]) - 1].ToString());
break;
case "4":
var (wasAppend, payload) = undo.Pop();
if (wasAppend)
{
text.Length -= payload.Length;
}
else
{
text.Append(payload);
}
break;
}
}
return printed.ToArray();
}
}