# Blogs Hub

### by Sumit Chourasia | Jun 04, 2020 | Category :coding | Tags : leetcodec-sharpडेटा-संरचनाआसानalgorithmstring

#### Valid Parentheses - String - Easy - LeetCode - मिनी टीवी

Given a string containing just the characters '(', ')', '{', '}', '[' and ']', determine if the input string is valid.

An input string is valid if:

Open brackets must be closed by the same type of brackets.

Open brackets must be closed in the correct order.

Note that an empty string is also considered valid.

Example 1:

Input: "()"

Output: true

Example 2:

Input: "()[]{}"

Output: true

Example 3:

Input: "(]"

Output: false

Example 4:

Input: "([)]"

Output: false

Example 5:

Input: "{[]}"

Output: true

Solution:

using System;
using System.Collections.Generic;
using System.Text;

{
public class IsValidSoln
{
public bool IsValid(string s)
{
var stack = new Stack<char>();
var map = new Dictionary<char, char>();

for (int i = 0; i < s.Length; i++)
{
if (map.ContainsKey(s[i]))
{
stack.Push(s[i]);
}
else
{
if(stack.Count == 0)
{
return false;
}

var ch = stack.Pop();
if(map[ch] != s[i])
{
return false;
}
}
}

if(stack.Count > 0)
{
return false;
}

return true;
}
}
}

Time Complexity: O(n)

Space Complexity: O(n)

Unit Tests:

using Microsoft.VisualStudio.TestTools.UnitTesting;
using System;
using System.Collections.Generic;
using System.Text;

namespace CodingUnitTest.Easy.String
{
[TestClass]
public class IsValidSolnTests
{
[TestMethod]
public void IsValidSoln_First()
{
var input = "()";
var output = true;
var res = new IsValidSoln().IsValid(input);

Assert.AreEqual(res, output);
}

[TestMethod]
public void IsValidSoln_Second()
{
var input = "()[]{}";
var output = true;
var res = new IsValidSoln().IsValid(input);

Assert.AreEqual(res, output);
}

[TestMethod]
public void IsValidSoln_Third()
{
var input = "(]";
var output = false;
var res = new IsValidSoln().IsValid(input);

Assert.AreEqual(res, output);
}

[TestMethod]
public void IsValidSoln_Fourth()
{
var input = "([)]";
var output = false;
var res = new IsValidSoln().IsValid(input);

Assert.AreEqual(res, output);
}

[TestMethod]
public void IsValidSoln_Fifth()
{
var input = "{[]}";
var output = true;
var res = new IsValidSoln().IsValid(input);

Assert.AreEqual(res, output);
}
}
}

Contributed By: Sumit Chourasia
Contributed By: Sumit Chourasia
Contributed By: Sumit Chourasia
Contributed By: Sumit Chourasia