OJ练习9——T20 valid parentheses

括号匹配。

输入只含有括号的字符串,判断是否匹配。

【思路】

考察栈。

但是小白没用过c++的栈,只好自己模拟一个。

小白的思路看起来是很清晰的,代码如下:

【my code】

bool isValid(string s) {
        int i=0;
        int j=-1;
        if(s.size()%2==1)
            return false;
        string strstack="";
        while(i<s.size()){
        if(s[i]=='('||s[i]=='['||s[i]=='{')
        {
            strstack.push_back(s[i++]);
            j++;
        }
        switch(s[i])
        {
            case ')':
                if(strstack[j]=='('){
                    j--;i++;}
                break;
            case '}':
                if(strstack[j]=='{'){
                    j--;i++;}
                break;
            case ']':
                if(strstack[j]=='['){
                    j--;i++;}
                break;
        }
        //i++;
        }//while
        if(j==0)
            return true;
    }

但是测试数据为“((”时,结果是true。WHY??

错因:j--能指示充当栈的字符串strstack的当前字符,却不能真正实现“出栈”,每次遇到左半边括号strstack都是push_back向后扩充,j只能指向前面的,而非栈顶的。

接着学习使用stack,按照原来的思路又出现了问题:

输入“}}”的情况时不能判断的。因此下面的思路perfect,用switch case是不合适的。

【other code】

class Solution {
public:
    bool isValid(string s) {
        // Start typing your C/C++ solution below
        // DO NOT write int main() function
        stack<char> st;
        
        for(int i = 0; i < s.size(); i++)
            if (s[i] == ')' || s[i] == ']' || s[i] == '}')
            {
                if (st.empty())
                    return false;
                else
                {
                    char c = st.top();
                    st.pop();
                    if ((c == '(' && s[i] != ')') || (c == '[' && s[i] != ']') || (c == '{' && s[i] != '}'))
                        return false;
                }
            }
            else
                st.push(s[i]);
                
        return st.empty();
    }
};

【分析】

由此看来,c++的stack数据结构使用方法:

stack<char> st;和vector类似;

char c = st.top();获取顶元素;

st.pop();弹出顶元素;

st.push(s[i]);入栈。

【总结】

待我找找自己代码的问题。

原文地址:https://www.cnblogs.com/ketchups-notes/p/4409076.html