0% found this document useful (0 votes)
42 views

Leetcode 20

This C++ code uses a stack to check the validity of parentheses in a string. It defines a bracketMatch function to check if a closing bracket matches an opening bracket. The isValid function iterates through the string, pushing opening brackets to the stack and popping matching closing brackets. It returns false if the stack is empty or the brackets don't match, otherwise it returns true if the stack is empty after iterating through the entire string.

Uploaded by

Dhruv Srivastava
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
42 views

Leetcode 20

This C++ code uses a stack to check the validity of parentheses in a string. It defines a bracketMatch function to check if a closing bracket matches an opening bracket. The isValid function iterates through the string, pushing opening brackets to the stack and popping matching closing brackets. It returns false if the stack is empty or the brackets don't match, otherwise it returns true if the stack is empty after iterating through the entire string.

Uploaded by

Dhruv Srivastava
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 2

Leetcode 20.

Valid Parentheses
class Solution {
public:

bool bracketMatch(char opening,char closing){

return (opening=='(' && closing==')') ||


(opening=='{' && closing=='}') || (opening=='[' &&
closing==']');

}
bool isValid(string s) {

stack<char> st;

for(auto x:s){

if(x=='(' || x=='{' || x=='[')


st.push(x);

else{

if(st.empty())
return false;

if(bracketMatch(st.top(),x)){
st.pop();
}
else{
return false;
}
}
}
return st.empty();
}
};

You might also like