LeetCode:Valid Parentheses

Valid Parentheses


Total Accepted: 111710  Total Submissions: 375574  Difficulty: Easy

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

Hide Tags
  Stack String
Hide Similar Problems
  (M) Generate Parentheses (H) Longest Valid Parentheses (H) Remove Invalid Parentheses














c++ code:

class Solution {
public:
    bool isValid(string s) {
        stack<char> ss;
        for(int i=0;i<s.size();i++) {
            if(!ss.empty() && isPair(ss.top(), s[i])) ss.pop();
            else ss.push(s[i]);
        }
        return ss.empty();
    }
    bool isPair(char left, char right) {
        return '['==left && ']'==right || '('==left && ')'==right || '{'==left && '}'==right;
    }
};


你可能感兴趣的:(LeetCode,String,stack)