- Valid Parentheses
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.
Example
Example 1:
Input: “([)]”
Output: False
Example 2:
Input: “()[]{}”
Output: True
Challenge
Use O(n) time, n is the number of parentheses.
解法1:用stack
class Solution {
public:
/**
* @param s: A string
* @return: whether the string is a valid parentheses
*/
bool isValidParentheses(string &s) {
int n = s.size();
if (n == 0) return true;
stack<char> st;
for (int i = 0; i < n; ++i) {
if (s[i] == '(' || s[i] == '[' || s[i] == '{') {
st.push(s[i]);
} else {
if (st.empty()) return false;
if (s[i] == ')' && st.top() != '(') return false;
if (s[i] == ']' && st.top() != '[') return false;
if (s[i] == '}' && st.top() != '{') return false;
st.pop();
}
}
if (!st.empty()) return false;
return true;
}
};