20 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.
Solution:
class Solution {
public:
bool isValid(string s) {
int n = s.size();
if ( n == 0 ) return true;
stack<char> stack;
for ( int i = 0; i <= n-1; i++ ) {
if ( s[i] == '(' or s[i] == '[' or s[i] == '{') stack.push(s[i]);
if ( s[i] == ')' or s[i] == ']' or s[i] == '}') {
if ( s[i] == ')' and (stack.empty() or stack.top() != '(' )) return false;
if ( s[i] == ']' and (stack.empty() or stack.top() != '[' )) return false;
if ( s[i] == '}' and (stack.empty() or stack.top() != '{' )) return false;
stack.pop();
}
}
return stack.empty();
}
};
Notes: note the difference between "" and ''.
char* ab = "123" ; //a string
char* cd = 'a' ; //a character.
A cleaner code using HashMap
class Solution {
public:
bool isValid(string s) {
unordered_map<char, char> map;
map['('] = ')';
map['['] = ']';
map['{'] = '}';
int n = s.size();
stack<char> left;
for ( int i = 0; i < n; i++ ) {
if ( map.find(s[i]) != map.end() ) left.push(s[i]);
else {
if ( left.empty() ) return false;
if ( map[left.top()] != s[i] ) return false;
left.pop();
}
}
return left.empty();
}
};