【LeetCode】20_Valid Parentheses

来源:互联网 发布:极光丛林果汁 淘宝 编辑:程序博客网 时间:2024/05/22 08:08

题目

Valid Parentheses

 

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.







解析

就是用堆栈来做。碰到[]对这种就出栈。

我刚开始以为只能是{}[]()这种,所以做了一个每次有(,[,{的时候就判断是否为空,不为空则false。后来它的案例中也有{()}这种,可见不用做这个判断。

我的代码如下

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

在参照别人的代码后,发现自己代码实在有点杂乱,改正优化后如下

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

简洁多了。

再来看看大神的代码

class Solution {public:    bool isValid(string s) {    string left = "([{";    string right = ")]}";    stack<char> stk;    for (auto c : s)     {        if (left.find(c) != string::npos)         {         stk.push (c);        }          else          {             if (stk.empty () || stk.top () != left[right.find (c)])                 return false;             else                stk.pop ();        }    }        return stk.empty();}};

大神的方法思路基本就是用两个对应的字符串,到时候去找相同的位置就可以把(){}[]进行匹配。

值得注意的是最后的return stk.empty();实在省事多了啊。


最后总结一下stack的用法吧,图片来自http://blog.csdn.net/morewindows/article/details/6950881







0 0