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;
}
#include <iostream>
#include <stack>
#include <string>
using namespace std;
int main(){
string s;
getline (cin, s);
stack<char> st;
for(int i = 0; i < s.size(); ++i)
{
if(s[i] == '(' || s[i] == '[' || s[i] == '{') st.push(s[i]);
if(s[i] == ')' && st.top() == '(')
{
st.pop();
continue;
}
if(s[i] == ')' && st.top() != '(')
{
cout << "No";
return 0;
}
if(s[i] == ']' && st.top() == '[')
{
st.pop();
continue;
}
if(s[i] == ']' && st.top() != '[')
{
cout << "No";
return 0;
}
if(s[i] == '}' && st.top() == '{')
{
st.pop();
continue;
}
if(s[i] == '}' && st.top() != '{')
{
cout<< "No";
return 0;
}
}
cout << endl;
cout << s << endl;
st.empty()? cout << "Yes" : cout << "No";
cout << endl << "Press any char and press 'Enter' : ";
cin >> s;
return 0;
}
Comments
Leave a comment