20— Valid Parentheses
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: true
Example 2:
Input: “()[]{}”
Output: true
Example 3:
Input: “(]”
Output: false
Example 4:
Input: “([)]”
Output: false
Example 5:
Input: “{[]}”
Output: true
C++代码:
class Solution {
public:
bool isValid(string s) {
int len = s.length();
vector<char> v;
if(len == 0) return true;
else if(len % 2 == 1 ) return false;
else{
for(int i = 0; i < len; i++) {
if(s[i] == '(' || s[i] == '{' ||s[i] == '[') {
v.push_back(s[i]);
}else if(s[i] == ')'){
if(v.empty() || v.back() != '(') return false;
else v.pop_back();
}else if(s[i] == '}'){
if(v.empty() || v.back() != '{') return false;
else v.pop_back();
}else{
if(v.empty()|| v.back() != '[') return false;
else v.pop_back();
}
}
}
return v.empty();
}
};
Complexity Analysis:
Time complexity : O( ).
Space complexity : O( ).
思路1:
- 简单的栈的应用