N

(Leet Code c++)Valid Parentheses 본문

Leet Code 알고리즘

(Leet Code c++)Valid Parentheses

naeunchan 2021. 7. 7. 09:05
728x90
반응형

20. Valid Parentheses

 

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

An input string is valid if:

  1. Open brackets must be closed by the same type of brackets.
  2. Open brackets must be closed in the correct order.

 

Example 1:

Input: s = "()" Output: true

Example 2:

Input: s = "()[]{}" Output: true

Example 3:

Input: s = "(]" Output: false

Example 4:

Input: s = "([)]" Output: false

Example 5:

Input: s = "{[]}" Output: true

 

Constraints:

  • 1 <= s.length <= 104
  • s consists of parentheses only '()[]{}'.

 

class Solution {
public:
    bool isValid(string s) {
        stack<char> stk;
        
        for(int i = 0; i < s.size(); i++){
            if(stk.empty()){
                stk.push(s[i]);
            }
            else{
                if(s[i] == ')'){
                    if(stk.top() == '('){
                        stk.pop();
                    }
                    else{
                        stk.push(s[i]);
                    }
                }
                else if(s[i] == '}'){
                    if(stk.top() == '{'){
                        stk.pop();
                    }
                    else{
                        stk.push(s[i]);
                    }
                }
                else if(s[i] == ']'){
                    if(stk.top() == '['){
                        stk.pop();
                    }
                    else{
                        stk.push(s[i]);
                    }
                }
                else{
                    stk.push(s[i]);
                }
            }
        }
        
        if(stk.empty()){
            return true;
        }
        else{
            return false;
        }
    }
};
728x90
반응형