leetcode之Valid Parentheses

来源:互联网 发布:mac虚拟机配置文件 编辑:程序博客网 时间:2024/06/05 15:51

原题如下:

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.

思路:这道题不算太难,但我刚开始却把它想的太简单了,导致提交3次才成功,简单说下思路,从头遍历字符串,利用Stack保存左括号,当遇到右括号时,判断当前元素是否与栈顶元素匹配,若匹配则出栈并继续遍历,否则返回false并结束遍历。

class Solution {public:    bool isValid(string s) {if(s.length() == 0)return true;stack<char>st;for(int i = 0; i < s.length(); i++){if(s[i] == '(')st.push('(');else if(s[i] == '[')st.push('[');else if(s[i] == '{')st.push('{');else{if(st.empty())return false;char c = st.top(); if((c == '(' && s[i] == ')') || (c == '[' && s[i] == ']') || (c == '{' && s[i] == '}') )st.pop();elsereturn false;}}if(st.empty())return true;return false;            }};
注:在利用st.top()取栈顶元素时要确保栈不为空,否则出现运行时错误。

0 0
原创粉丝点击