Created
February 10, 2017 13:43
Reddit Daily Programmer 298 Easy
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
using System.Collections.Generic; | |
using System.Linq; | |
using System.Text; | |
namespace Reddit | |
{ | |
internal static class Easy | |
{ | |
internal static string Run(string input) | |
{ | |
var collection = new LinkedList<char>(input); | |
Rule2(collection); | |
Rule1(collection); | |
var builder = new StringBuilder(); | |
foreach (char value in collection) | |
{ | |
builder.Append(value); | |
} | |
return builder.Length == 0 ? null : builder.ToString(); | |
} | |
internal class Pair | |
{ | |
internal LinkedListNode<char> Left; | |
internal LinkedListNode<char> Right; | |
} | |
internal static List<Pair> Parse(LinkedList<char> collection) | |
{ | |
var items = new List<Pair>(); | |
var stack = new Stack<LinkedListNode<char>>(); | |
var current = collection.First; | |
while (current != null) | |
{ | |
char c = current.Value; | |
if (c == '(') | |
{ | |
stack.Push(current); | |
} | |
else | |
{ | |
if (c == ')') | |
{ | |
if (stack.Count > 0) | |
{ | |
var previous = stack.Pop(); | |
var item = new Pair(); | |
item.Left = previous; | |
item.Right = current; | |
items.Add(item); | |
} | |
} | |
} | |
current = current.Next; | |
} | |
return items; | |
} | |
internal static void Rule1(LinkedList<char> collection) | |
{ | |
var items = Parse(collection); | |
foreach (var item in items) | |
{ | |
var left = item.Left; | |
var right = item.Right; | |
if (items.Any(e => | |
e.Left.Previous == left && | |
e.Right.Next == right)) | |
{ | |
collection.Remove(left); | |
collection.Remove(right); | |
} | |
} | |
} | |
internal static void Rule2(LinkedList<char> collection) | |
{ | |
var items = Parse(collection); | |
foreach (var item in items) | |
{ | |
var left = item.Left; | |
var right = item.Right; | |
if (left.Next == right) | |
{ | |
collection.Remove(left); | |
collection.Remove(right); | |
} | |
} | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment