C# program to Given a string containing just the characters '(', ')', '{', '}', '[' and ']', determine if the input string is valid.
Here's a C# program that determines if a given string containing only the characters '(', ')', '{', '}', '[' and ']' is valid:
using System;
using System.Collections.Generic;
class Program
{
static void Main()
{
string inputString = "{[()]}";
bool isValid = IsValidParentheses(inputString);
if (isValid)
{
Console.WriteLine("The input string is valid.");
}
else
{
Console.WriteLine("The input string is not valid.");
}
}
static bool IsValidParentheses(string inputString)
{
Stack stack = new Stack();
foreach (char c in inputString)
{
if (c == '(' || c == '{' || c == '[')
{
stack.Push(c);
}
else if (c == ')' || c == '}' || c == ']')
{
if (stack.Count == 0)
{
return false;
}
char top = stack.Pop();
if ((c == ')' && top != '(') || (c == '}' && top != '{') || (c == ']' && top != '['))
{
return false;
}
}
}
return stack.Count == 0;
}
}
In this program, we have the 'IsValidParentheses' method that takes a string as input and returns a boolean indicating whether the input string is valid.
We use a stack data structure to keep track of the opening parentheses. We iterate through each character in the input string. If we encounter an opening parenthesis ('(', '{', '['), we push it onto the stack. If we encounter a closing parenthesis (')', '}', ']'), we check if the stack is empty. If it is empty, it means there is no corresponding opening parenthesis, and we return 'false'. Otherwise, we pop the top element from the stack and compare it with the current closing parenthesis. If they don't match, we return 'false'.
After iterating through all characters in the input string, if there are any remaining parentheses left in the stack, it means there are unmatched opening parentheses, and we return 'false'. Otherwise, we return 'true'.
In the example above, the output would be:
The input string is valid.
The input string "{[()]}" contains balanced and properly nested parentheses, so the program determines that the input string is valid.