Given a string of round, curly, and square open and closing brackets, return whether the brackets are balanced (well-formed).
For example, given the string "([])[]({})", you should return true.
Given the string "([)]" or "((()", you should return false.
Example:
Input: s = "([])[]{})
Output: Valid Parentheses
Approach
C++
#include <bits/stdc++.h>using namespace std;//function to check valid//parenthesesbool isValid(string s){//stack to hold the opening bracketsstack<char> st;int n = s.size();for (int i = 0; i < n; i++){//if open bracket push into the stackif (s[i] == '(' || s[i] == '{' || s[i] == '[')st.push(s[i]);else{//stack is emptyif (st.empty())return false;//closing bracket not matches with the top//of stack return falseelse if (s[i] == ')' && st.top() != '(')return false;else if (s[i] == ']' && st.top() != '[')return false;else if (s[i] == '}' && st.top() != '{')return false;st.pop();}}if (!st.empty())return false;return true;}int main(){string str = "([])[]({})";if (isValid(str))cout << "Valid Parentheses\n";elsecout << "Not Valid Parenthese\n";return 0;}//Time Complexity:O(n)//Space Complexity:O(n)
No comments:
Post a Comment