diff --git a/Algorithms.Tests/Strings/ValidParenthesesTests.cs b/Algorithms.Tests/Strings/ValidParenthesesTests.cs new file mode 100644 index 00000000..66ca55c3 --- /dev/null +++ b/Algorithms.Tests/Strings/ValidParenthesesTests.cs @@ -0,0 +1,32 @@ +using System; +using NUnit.Framework; +using Algorithms.Strings; + +namespace Algorithms.Tests.Strings +{ + public static class ValidParenthesesTests + { + [TestCase("([{}])")] + public static void IsValidParentheses_TrueExpected(string parentheses) + { + // Arrange + // Act + var isValidParentheses = ValidParentheses.IsValidParentheses(parentheses); + + // Assert + Assert.That(isValidParentheses, Is.True); + } + + [TestCase("([)[}")] + [TestCase("([}}])")] + public static void IsValidParentheses_FalseExpected(string parentheses) + { + // Arrange + // Act + var isValidParentheses = ValidParentheses.IsValidParentheses(parentheses); + + // Assert + Assert.That(isValidParentheses, Is.False); + } + } +} diff --git a/Algorithms/Strings/ValidParentheses.cs b/Algorithms/Strings/ValidParentheses.cs new file mode 100644 index 00000000..4ccd58d9 --- /dev/null +++ b/Algorithms/Strings/ValidParentheses.cs @@ -0,0 +1,67 @@ +using System; +using System.Collections.Generic; + +namespace Algorithms.Strings +{ + /// + /// This is a class for checking if the parentheses is valid. + /// A valid parentheses should have opening brace and closing brace. + /// + public static class ValidParentheses + { + /// + /// Function to check if the parentheses is valid. + /// + /// String to be checked. + public static bool IsValidParentheses(string parentheses) + { + if (parentheses.Length % 2 != 0) + { + return false; + } + + Stack stack = new Stack(); + + foreach(char c in parentheses) + { + switch (c) + { + case '(': + case '{': + case '[': + stack.Push(c); + break; + + case ')': + if (stack.Count == 0 || stack.Pop() != '(') + { + return false; + } + + break; + + case '}': + if (stack.Count == 0 || stack.Pop() != '{') + { + return false; + } + + break; + + case ']': + if (stack.Count == 0 || stack.Pop() != '[') + { + return false; + } + + break; + + default: + return false; + } + } + + return stack.Count == 0; + } + } +} diff --git a/README.md b/README.md index b9933f9f..d57f3446 100644 --- a/README.md +++ b/README.md @@ -213,6 +213,7 @@ find more than one implementation for the same objective but using different alg * [Longest Consecutive Character](./Algorithms/Strings/GeneralStringAlgorithms.cs) * [Palindrome Checker](./Algorithms/Strings/Palindrome.cs) * [Get all permutations of a string](./Algorithms/Strings/Permutation.cs) + * [Valid Parentheses Checker](./Algorithms/Strings/ValidParentheses.cs) * [Other](./Algorithms/Other) * [Fermat Prime Checker](./Algorithms/Other/FermatPrimeChecker.cs) * [Sieve of Eratosthenes](./Algorithms/Other/SieveOfEratosthenes.cs)