Leetcode刷题记录---20. Valid Parentheses

菜鸡我决定提升一下自己代码能力,为了不打击自己的自信心,这次就先从简单的开始了

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;
        }
    }
};


幸好结果还行,我的心脏还能承受得起哈哈

posted @ 2020-03-31 12:32  c_y_yuan  阅读(82)  评论(0编辑  收藏  举报