Valid Parentheses

来源:互联网 发布:萌牙电动牙刷知乎 编辑:程序博客网 时间:2024/05/16 07:19

https://oj.leetcode.com/problems/valid-parentheses/


1、题目要求:给定一个字符串s只包含"{", "}", "[", "]", "(", ")",这六种字符,判断字符串s是否有效,即判断s中的每个括号正确匹配。

例:"( )"和"{ ( ) [ ] }"都是有效的,而"{ ]"是无效的。


2、解题思路:如果遇到左括号,则将其压入栈中,如果遇到右括号,则将其与栈顶元素比较是否匹配。如果匹配成功,则弹出栈顶元素,如果匹配失败则返回false,最后判断栈是否为空,即判断是否所有的左括号都正确匹配。


class Solution {public:    bool isValid(string s) {        string result;stack<char> st;string::iterator it = s.begin();while (it != s.end()){switch (*it){case '(':st.push('(');break;case '[':st.push('[');break;case '{':st.push('{');break;case ')':if (!st.empty() && st.top() == '(')st.pop();elsereturn false;break;case ']':if (!st.empty() && st.top() == '[')st.pop();elsereturn false;break;case '}':if (!st.empty() && st.top() == '{')st.pop();elsereturn false;break;default:break;}it++;}if (st.empty())return true;elsereturn false;    }};






0 0
原创粉丝点击