leetcode - Valid Parentheses

来源:互联网 发布:阿基里斯悖论 知乎 编辑:程序博客网 时间:2024/06/03 17:41

Given a string containing just the characters '('')''{''}''[' and ']', determine if the input string is valid.

The brackets must close in the correct order, "()" and "()[]{}" are all valid but "(]" and "([)]" are not.

class Solution {public:    bool isValid(std::string s) {std::stack<char> st;for (int i = 0; i < s.size(); i++){if(s[i] == '(' || s[i] == '[' || s[i] == '{') st.push(s[i]);else if(s[i] == ')'){if(st.empty()) return false;if(s[i] == ')' && st.top() == '(')st.pop();elsereturn false;}else if(s[i] == ']'){if(st.empty()) return false;if(s[i] == ']' && st.top() == '[')st.pop();elsereturn false;}else if(s[i] == '}'){if(st.empty()) return false;if(s[i] == '}' && st.top() == '{')st.pop();elsereturn false;}else{return false;}}if(st.empty())return true;elsereturn false;    }};


0 0
原创粉丝点击