leetcode解题报告(7):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.

分析

遇到这种括号匹配的问题,当然要用栈来写。先把string的第一个元素压入栈,再从第二个元素开始遍历,如果栈顶元素为和当前string的元素相匹配,就把该元素出栈。如果在遍历期间堆栈为空了,比如输入的是:

[]{}()

那么在i=1的时候栈就会为空,这时候取栈顶元素是没有意义的。因此如果遍历期间发现栈为空,就直接把当前的string元素压入栈中。

另外,如果输入的string的长度不是偶数,那么肯定是不匹配的,在一开始的时候做这个判断,可以筛掉很多种不匹配的情况。

总之,如果输入的string是匹配的,那么最终的栈一定为空。

为了判断栈顶元素和当前string的元素是否相匹配,可以定义一个名为isOK的函数。

代码如下:

class Solution {
public:
    bool isOK(const char &a,const char &b){
        if((a == '(' && b == ')')
            || (a == '[' && b == ']')
            || (a == '{' && b == '}'))
            return true;
        else
            return false;
        
    }
    bool isValid(string s) {
        if(s.size() % 2 != 0)return false;
        stack<char>sc;
        sc.push(s[0]);
        for(int i = 1; i != s.size(); ++i){
            if(sc.empty())
                sc.push(s[i]);
            else{
                if(isOK(sc.top(),s[i]))
                    sc.pop();
                else
                    sc.push(s[i]);
            }
        }
        return sc.empty();
    }
};

下面是另一种更优雅的解法:
https://leetcode.com/problems/valid-parentheses/#/solutions

class Solution {
public:
    bool isValid(string s) {
      if(s.size() % 2 != 0)return false;
      stack<char>paren;
      for(char& c : s){
        switch(c){
            case '(':
            case '[':
            case '{':paren.push(c);break;
            case ')':if(paren.empty() || paren.top() != '(')return false;paren.pop();break;
            case ']':if(paren.empty() || paren.top() != '[')return false;paren.pop();break;
            case '}':if(paren.empty() || paren.top() != '{')return false;paren.pop();break;
            default:;
        }
      }
      return paren.empty();
    }
};
posted @ 2017-04-23 15:59  larryking  阅读(141)  评论(0编辑  收藏  举报