leetcode Valid Parentheses

来源:互联网 发布:淘宝原图制作方法 编辑:程序博客网 时间:2024/05/29 10:23

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.

左括号: ( { [
右括号: ) } ]
若地一个非左括号,则return false。 遇到左括号就进栈, 直到遇到第一个右括号, 和栈定元素比较, 若匹配, 出栈, 否则返回false。 直到遍历最后一个字符, 如果此时栈为空,return true, 否则 false。

class Solution{    public:      bool isValid(string s)       {          if (s=="")          {              return false;          }          stack<char> str;          int i = 0;          while (i<s.size())          {              if (s[i] == '(' || s[i] == '[' || s[i] == '{')              {                  str.push(s[i]);              }              else              {                  if (str.empty())                  {                       return false;                  }                  else                  {                      char tmp = str.top();                      if ( (s[i]==')'&& tmp=='(') ||       (s[i]==']'&&tmp=='[')                               || (s[i]=='}'&&tmp=='{') )                      {                          str.pop();                      }                      else                      {                          return false;                      }                 }              }              i++;           }           if (str.empty())           {               return true;           }           return false;       }};
0 0
原创粉丝点击