Octavio Licea
BAN USER- 0of 0 votes
AnswersGiven a series of parenthesis and bracket with the possible pairs of (), {}, [], write a method that will return true if the series is balanced, and false otherwise.
- Octavio Licea in United States
for example i.e.
"()" => true
"({})" => true
"([]()){}" => true
"([)]{}" => false, the square bracket '[' does not have a matching closing bracket ']'| Report Duplicate | Flag | PURGE
Algorithm
using System;
using System.Collections.Generic;
using Microsoft.VisualStudio.TestTools.UnitTesting;
namespace AlgorithmsTests
{
[TestClass]
public class ReversePolishNotation
{
private int Calculate(string s)
{
if (string.IsNullOrEmpty(s))
return 0;
int result = 0;
Queue<int> queue = new Queue<int>();
string[] items = s.Split(new[] { ' ' });
for (int i = 0; i < items.Length; i++)
{
int n;
if (int.TryParse(items[i], out n))
{
//n has the int value
}
else if (IsOperator(items[i]))
{
int a = queue.Dequeue();
int b = queue.Dequeue();
n = Operate(items[i], a, b);
}
// enqueue the result or the number
queue.Enqueue(n);
}
//return the last number form the queue
return queue.Dequeue();
}
private int Operate(string o, int a, int b)
{
switch (o)
{
case "+":
return a + b;
case "-":
return a - b;
case "*":
return a * b;
case "/":
return a / b;
default:
throw new ApplicationException("Operator not suported.");
}
}
private bool IsOperator(string s)
{
return s.Equals("+", StringComparison.OrdinalIgnoreCase) ||
s.Equals("-", StringComparison.OrdinalIgnoreCase) ||
s.Equals("*", StringComparison.OrdinalIgnoreCase) ||
s.Equals("/", StringComparison.OrdinalIgnoreCase);
}
[TestMethod]
public void RVN_Test()
{
Assert.AreEqual(0, Calculate(string.Empty));
Assert.AreEqual(7, Calculate("3 4 +"));
Assert.AreEqual(2, Calculate("6 3 /"));
Assert.AreEqual(19, Calculate("3 5 * 4 +"));
Assert.AreEqual(1, Calculate("10 2 / 4 -"));
}
}
}
using System;
using Microsoft.VisualStudio.TestTools.UnitTesting;
namespace AlgorithmsTests
{
[TestClass]
public class ReverseATree
{
[TestMethod]
public void Reverse_Test()
{
/* 1
/ \
2 4
/ \
3 5
*/
Node head = new Node()
{
Value = 1,
Left = new Node()
{
Value = 2,
Left = new Node()
{
Value = 3
}
},
Right = new Node()
{
Value = 4,
Right = new Node()
{
Value = 5
}
}
};
Reverse(head);
Assert.AreEqual(1, head.Value);
Assert.AreEqual(4, head.Left.Value);
Assert.AreEqual(2, head.Right.Value);
Assert.AreEqual(5, head.Left.Left.Value);
Assert.AreEqual(3, head.Right.Right.Value);
}
private void Reverse(Node n)
{
if (n == null)
{
return;
}
Node tmp = n.Left;
n.Left = n.Right;
n.Right = tmp;
Reverse(n.Left);
Reverse(n.Right);
}
}
class Node
{
public Object Value;
public Node Left;
public Node Right;
}
}
- Octavio Licea February 29, 2016