Search
 
SCRIPT & CODE EXAMPLE
 
CODE EXAMPLE FOR CPP

cpp valid parentheses

//AIGHT BRU, LESSGO!
//valid parantheses. or balanced parantheses
#include<iostream>
#include<stack>
using namespace std;
bool isvalid(string s)
{
	int n=s.length();
	bool ans=true;
	stack<char>st; // creating a stack to work with.
	for(int i=0;i<n;i++)
	{
		if(s[i]=='(' || s[i]=='{' || s[i]=='[' ) st.push(s[i]); // directly putting all opening brackets in.
		else if(s[i]==')')//check if there is a closing bracket on top of stack.
		{
			if(!st.empty() && st.top()=='(') st.pop();
			else 
			{
				ans=false;
				break;
			}
		}
		else if(s[i]==']')//check if there is a closing bracket on top of stack.
		{
			if(!st.empty() && st.top()=='[') st.pop();
			else 
			{
				ans=false;
				break;
			}
		}
		else if(s[i]=='}')//check if there is a closing bracket on top of stack.
		{
			if(!st.empty() && st.top()=='{') st.pop();
			else 
			{
				ans=false; // coz we can only have brackets and not other characters.
				break;
			}
		}
		else 
		return false;
	}
	if(!st.empty()) return false; // check if there are still some brackets (opening) left in stack.
	else return ans;
}
int main()
{
	string s;
	cin>>s;
	if(isvalid(s)) cout<<"yes";
	else cout<<"no";
}
 
PREVIOUS NEXT
Tagged: #cpp #valid #parentheses
ADD COMMENT
Topic
Name
2+4 =