Validation of Input string With balanced parentheses- Learn how to write a program to find a string of parentheses is valid or not.
For Example Consider the following Inputs with balanced parentheses.
Input-1
{}{}
output-1
valid string
Input-2
}{{}}
0utput-2
invalid string
Note
For valid string , parentheses must be open and need to have closed parentheses for the opened one.
C# -Program to find whether the string with balanced parentheses is valid or invalid
class Program
{
static void Main(string[] args)
{
//input string for validation
String s = "{{{}}}";
int counter = 0;
//counter variable increments if character is '{ ' and
//counter variable decrements if character is '}'
//finally for every balanced open parenthesis , it required a closed parenthesis as a rule.
//if for every balanced open parenthesis finds corresponding balanced closed parenthesis
// then counter becomes zero which is a valid string
//if counter less than zero then it is a invalid string.
for (int i = 0; i <s.Length ; i++)
{
if(s[i]=='{')
{
counter++;
}
if(s[i]=='}')
{
counter--;
if(counter<0)
{
break;
}
}
}
if(counter==0)
{
Console.WriteLine("valid string ");
}
if(counter < 0)
{
Console.WriteLine("in valid string ");
}
}
}
Output
valid string