首页 > 其他 > 详细

leetcode Valid Parentheses

时间:2015-08-01 01:10:55      阅读:210      评论:0      收藏:0      [点我收藏+]

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;
       }
};

版权声明:本文为博主原创文章,未经博主允许不得转载。

leetcode Valid Parentheses

原文:http://blog.csdn.net/nizhannizhan/article/details/47156937

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!