Leetcode brush title record --- 20. Valid Parentheses

Chicken dish I decided to raise my own ability codes, in order not to blow their own self-confidence, this time to start with a simple start up

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

An input string is valid if:

Open brackets must be closed by the same type of brackets.
Open brackets must be closed in the correct order.
Note that an empty string is also considered valid.

class Solution {
public:
     bool isValid(string s) {
        stack<char> stack;
        char c;
        int i = 0;
       
        while(s[i] != '\0'){
            c= s[i];
            //cout << "c=" << c << endl;
            if(c == '(' || c == '{' || c == '['){
                stack.push(c);
            }else if(!stack.empty() && (( c == ')' && stack.top() == '(') || (c == '}' && stack.top() == '{') || (c == ']' && stack.top() == '[') )){
                stack.pop();
            
            }else {
                stack.push(c);
            }
          i++;
        }

        if(stack.empty()){
            return true;
        }else{
            return false;
        }
    }
};


Fortunately, okay, my heart still afford ha ha

Guess you like

Origin www.cnblogs.com/yuyuan-bb/p/12604358.html