0% found this document useful (0 votes)
9 views1 page

Valid Parentheses

The provided code defines a class Solution with a method isValid that checks if a string of parentheses is valid. It uses a stack to track opening brackets and ensures that each closing bracket corresponds to the correct opening bracket. The function returns true if all brackets are matched and false otherwise.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as TXT, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
9 views1 page

Valid Parentheses

The provided code defines a class Solution with a method isValid that checks if a string of parentheses is valid. It uses a stack to track opening brackets and ensures that each closing bracket corresponds to the correct opening bracket. The function returns true if all brackets are matched and false otherwise.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as TXT, PDF, TXT or read online on Scribd
You are on page 1/ 1

class Solution {

public:
bool isValid(string s) {
stack<int> t;

int n = s.size();
if (n == 1)
return false;
for (int i = 0; i < n; i++) {
if (s[i] == ']') {
if (t.size() == 0)
return false;
if (t.top() != '[')
return false;
else {
t.pop();
}
}
else if (s[i] == ')') {
if (t.size() == 0)
return false;

if (t.top() != '(')
return false;
else
t.pop();
}
else if (s[i] == '}') {
if (t.size() == 0)
return false;

if (t.top() != '{')
return false;
else
t.pop();
}
else
t.push(s[i]);
}
return t.size() == 0;
}
};

You might also like