leetcode-Valid Parenthese

括號匹配

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

The brackets must close in the correct order, “()” and “()[]{}” are all valid but “(]” and “([)]” are not.

Subscribe to see which companies asked this question.

class Solution {
public:
    bool isValid(string s) {
        char stack[5000];
        int top = 0;
        int len = s.size();
        for(int i = 0 ; i < len;i++ ){
            if(!top){
                stack[top++] = s[i];
            }
            else{
                switch(s[i]){
                    case '(':
                    case '[':
                    case '{':stack[top++] = s[i];break;
                    case ')':
                            if(stack[top-1] == '('){
                                top--;                            
                            }
                            else{
                                return false;
                            }
                            break;
                    case ']':
                            if(stack[top-1] == '['){
                                top--;
                            }
                            else{
                                return false;
                            }
                            break;
                    case '}':
                            if(stack[top-1] == '{'){
                                top--;
                            }
                            else{
                                return false;
                            }
                            break;
                    default:break;
                }
            }
        }
        if(top == 0){
            return true;
        }
        return false;
    }
};
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章