首页 > 代码库 > leetcode第20题--Valid Parentheses

leetcode第20题--Valid Parentheses

Problem:

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.

判断输入的括号是不是合法。这题在大二的时候就遇到过了。想不到我的记性这么好。因为当时我什么都不懂,刚学数据结构,然后有个ACMer是助教,他给我讲解了这题。然后我就一直都记得了。也不知道那个师兄现在在哪里牛逼。

回到题目,就是用栈实现。

class Solution {    private:    char anti(char c)    {        if (c == ])            return [;        if (c == ))            return (;        if (c == })            return {;    }public:    bool isValid(string s) {        int len = s.size();        if (len%2)        { return false;}        if(s.size() == 0 || s[0] == ) || s[0] == ] || s[0] == })            return false;        stack<char> st;        for (int i = 0; i < len; i++)        {            if (s[i] == ( || s[i] == { || s[i] == [)                st.push(s[i]);            else                if (st.top() == anti(s[i]))                    st.pop();                else                    return false;        }        if (st.empty())            return true;        else            return false;    }};

代码写得有点挫,大概就是这个思路,然后Accept了

leetcode第20题--Valid Parentheses