Exercises on stacks and queues [3]

The study arrangement is based on "Code Caprice" leetcode20

A simple question, I have done it myself before, but it took me a day to think about the loopholes in the rewritten code! ! !

Idea: According to the study arrangement of "Dilu", it is natural to think in the direction of queue or stack. Obviously, the characteristics of queue FIFO cannot meet the requirements, so consider stack.

Because of the matching, I also define an unordered_map to perform bracket matching, which is used to match the top element of the stack to the next element.

i=0;

1. We first compare whether the two brackets before and after the string s are closed. If they are closed, they will not be pushed onto the stack. If they are not closed, they will be pushed onto the stack. Finally, i=i+2;

2. When the stack is empty, if the two brackets before and after the string s are not closed, the current element is pushed onto the stack, and then i=i+1;

3. When the stack is not empty, execute 1 if 1 is satisfied;

4. When the stack is not empty, if the next element is closed to the top element of the stack, delete the top element of the stack, and then i=i+1;

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

The idea is not difficult to think of, but what made me fall into the pit is that when I created the unordered_map and stored the key-value pair, I didn't pay attention, but stored all the left and right parentheses, which led to three examples that failed in the end. , take the following string as an example

(){}}{ 

! ! ! ! ! ! ! ! ! cry to death

 When I finally squatted in the pit, I suddenly thought that the condition of closing brackets is: the left and right brackets must be closed correctly . If the left and right brackets are stored in the form of key-value pairs, it will appear that } { is also a closing bracket! ! !

Hey, just because of this question, I didn't complete the task of brushing the question yesterday, and it was still an easy question! want to cry without tears

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=324158165&siteId=291194637