Answer to Question #159441 in C# for shakib

Question #159441

Given a string s 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.


Example 1:


Input: s = "()"

Output: true


Example 2:


Input: s = "()[]{}"

Output: true


Example 3:


Input: s = "(]"

Output: false


Example 4:


Input: s = "([)]"

Output: false


Example 5:


Input: s = "{[]}"

Output: true


*Your program output should follow the example in the instruction.


* The program should print the input parentheses and the output (true/false).                                                                     



*Parentheses.txt : ((()))


You are required to follow this program template I provide and use stack to solve the problem. Please test the program.



#include <stdio.h>

#include <stdlib.h>


// This is where the parentheses are stored in memory

char buffer[1024];

char stack_pop();

void stack_push(char ch);

int stack_size();



int main(){

FILE *fp;

  // The parentheses sequences is in the parentheses.txt file.

  fp=fopen("parentheses.txt","r");

  if(fp==NULL){

  printf("The input file does not exist.\n");

  exit(-1);

  }

  // Read the parenthese sequences into buffer array.

  fgets(buffer,1024,fp);

  //printf("%s",buffer);

}


// The pop operation in the stack. To be done.

char stack_pop(){

return ')';

}



// The push operation in the stack. To be done.

void stack_push(char ch){

}



// The number of elements in the stack. To be done.

int stack_size(){

return 0;

}


1
Expert's answer
2021-01-29T06:49:22-0500
using System;


namespace Questions
{
    class Program
    {
        public static bool IsValidInput(string input)
        {
            int counter = 0;
            if (input.Length == 0)
                return true;


            if (input.Length % 2 != 0)
                return false;


            for(int i = 0; i < input.Length; i++)
            {
                if (input[i] == ')' || input[i] == ']' || input[i] == '}')
                {
                    if (counter == 0)
                        return false;
                    counter--;
                }
                else
                    counter++;
            }
            return counter == 0;
        }
        static void Main(string[] args)
        {
            Console.Write("Enter string containing (,),[,],{,}");
            string input = Console.ReadLine();
            Console.WriteLine(IsValidInput(input));
            Console.ReadKey();
        }
    }
}

Need a fast expert's response?

Submit order

and get a quick answer at the best price

for any assignment or question with DETAILED EXPLANATIONS!

Comments

No comments. Be the first!

Leave a comment

LATEST TUTORIALS
New on Blog
APPROVED BY CLIENTS