https://leetcode.com/problems/valid-parentheses/description/
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.
Example 1:
Input: "()" Output: trueExample 2:
Input: "()[]{}" Output: trueExample 3:
Input: "(]" Output: falseExample 4:
Input: "([)]" Output: falseExample 5:
Input: "{[]}" Output: true题解:
class Solution { public: bool isValid(string s) { stack<char> st; int n = s.length(); if (n == 0) { return true; } int i = 0; st.push(s[i++]); while (i < n) { if (s[i] == '(' || s[i] == '{' || s[i] == '[') { st.push(s[i++]); } else if (s[i] == ')' || s[i] == '}' || s[i] == ']') { if (st.empty() == true) { return false; } char tmp = st.top(); st.pop(); if (tmp == '(' && s[i] == ')') { i++; continue; } if (tmp == '[' && s[i] == ']') { i++; continue; } if (tmp == '{' && s[i] == '}') { i++; continue; } return false; } } return st.empty(); } };