Opening and Closing parenthesis

grraja.in

New member
Joined
Apr 24, 2015
Messages
2
Programming Experience
3-5
You are given a string made up of only these bracket characters: ()[]{}. A string is said to have valid
brackets if and only if for every opening bracket, there is the corresponding closing bracket after it.
say For example, ?()[]{}? and ?[({}())[]]? have valid brackets, but ?(){]? and ?{[}]? are not valid
brackets.....


Write a program to accept a string as input, and determine whether the string has valid or invalid
brackets. Print ?valid? or ?invalid? as the output.
 
So, basically, "here's my assignment, you do it for me"? No, I'm afraid not. We're not a free homework service. You show us what you've tried and tell us where you're stuck and we'll try to help you fix the issue.
 
Guru's this is Not Assignment .....:)

I tried with

string input = "[({}())[](";
Match match = Regex.Match(input, @"[({}())[]]", RegexOptions.IgnoreCase);
// Here we check the Match instance.
if (match.Success)
{
Console.WriteLine(" First one : Valid");
}
else
{
Console.WriteLine(" First one : InValid");
}


string input1 = "{[}]";
Match match1 = Regex.Match(input1, @"[({}())[]]", RegexOptions.IgnoreCase);
// Here we check the Match instance.
if (match1.Success)
{
Console.WriteLine("Second one : Valid");
}
else
{
Console.WriteLine("Second one : InValid");
}


Console.ReadLine();


Both is Coming Valid ..... But the Second one should be Invalid....i tried using Dictionary

it works :

string str = "{}[]()";
Dictionary<string, string> vGet = new Dictionary<string, string>();
vGet.Add("{", "}");
vGet.Add("[", "]");
vGet.Add("(", ")");


if (vGet.ContainsKey("{"))
{
Response.Write(vGet["{"].ToString().Trim());
Response.Write("Valid");
}
else
{
Response.Write("InValid");
}

if I give string as " [({}())[]( " .... this doesn't work..... i tried using "stack" and "queue" too....target is Whatever way open parenthesis i give it should have Close Parenthesis...for example, whatever number i give we say Prime / even / odd etc., or not similar to that ....hope guys got it????. any help from guru's...:)
 
Last edited:
None of your attempts make any sense to me. Using a stack is the way to go. You need to read the string character by character. If you read an opening bracket, brace or parenthesis then you would push it onto the stack. When you read a closing bracket, brace or parenthesis, you pop the last item off the stack and compare the two. If they are not the same type then the string is invalid, otherwise you keep going. If you get to the end of the string with no mismatches and the stack is empty then the string was valid, otherwise it is invalid.
 
Back
Top Bottom