20. Valid Parentheses

来源:互联网 发布:淘宝网买东西的步骤 编辑:程序博客网 时间:2024/06/03 22: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.

Subscribe to see which companies asked this question.


容易理解,此题位简单堆栈问题,将信息推入栈中,右括号出现时pop判断是否符合标准即可,代码如下:

class Solution {public:    int isValid(string s) {        int i=0;        vector<int> v;        for(i=0;i<s.size();i++){        if(s[i]=='(')  v.push_back(1);        if(s[i]=='[')  v.push_back(2);        if(s[i]=='{')  v.push_back(3);              if(s[i]==')'){              if(v.empty()) return false;              if(v[v.size()-1]==1) v.pop_back();              else return false;              }              if(s[i]==']'){              if(v.empty()) return false;              if(v[v.size()-1]==2) v.pop_back();              else return false;              }              if(s[i]=='}'){              if(v.empty()) return false;              if(v[v.size()-1]==3) v.pop_back();              else return false;              }        }        if(!v.empty()) return false;        return true;    }};


原创粉丝点击