leetcode20[Valid Parentheses]

括号配对问题,题目如下:

Given a string containing just the characters '(', ')', '{', '}', '[' and ']', determine if the input string is valid.
An input string is valid if:

  1. Open brackets must be closed by the same type of brackets
  2. Open brackets must be closed in the correct order.

Note that an empty string is also considered valid.

例如`[{()}]`,`[]{}()`都是正确的配对,`{][}`,`)`都是错误的配对,空串也认为是正确的配对。这是一个栈的问题,可以通过进栈出栈来进行匹配。 栈的特性就是先进后出,首先遍历字符串,将左括号依次进栈直到遇到右括号,然后进行出栈与对比,若有一次不匹配则直接返回false,直到栈为空或遇到左括号。然后继续遍历字符串和进栈操作,直到遍历完成,最后返回true。

class Solution {
public:
    bool isValid(string s) {
        string left = "([{";
        string right = ")]}";
        stack<char> st;

        for(int i=0;i!=s.size();++i)
        {
            if(right.find(s[i])!=right.npos)
                return false;
            while(left.find(s[i])!=left.npos)
            {
                st.push(s[i]);
                ++i;
            }
            while(!st.empty()&&left.find(s[i])==left.npos)
            {
                if(left.find(st.top())!=right.find(s[i]))
                    return false;
                else
                    st.pop();
                ++i;
            }
            --i;
        }
        return true;
    }
};

另一种比较巧妙的方法就是每遇到一个左括号,就将对应的右括号入栈,遇到右括号就与栈顶元素比较,若相等则出栈并继续,若不相等则直接返回False。另外如果栈为空时遇到右括号,也返回false。最后若栈为空则匹配完成,返回true。

class Solution {
public:
    bool isValid(string s) {
        stack<char> st;

        for(int i=0;i!=s.size();++i)
        {
            if(s[i]=='(')
                st.push(')');
            else if(s[i]=='[')
                st.push(']');
            else if(s[i]=='{')
                st.push('}');
            else if(st.empty()||st.top()!=s[i])
                return false;
            else
                st.pop();
        }
        return st.empty();
    }
};


 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章