Skip to content

Instantly share code, notes, and snippets.

@zhoutuo
Created February 12, 2013 18:54
Show Gist options
  • Save zhoutuo/4772272 to your computer and use it in GitHub Desktop.
Save zhoutuo/4772272 to your computer and use it in GitHub Desktop.
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.
class Solution {
public:
bool isValid(string s) {
// Start typing your C/C++ solution below
// DO NOT write int main() function
stack<char> checker;
for(int i = 0; i < s.length() ; ++i) {
char cur = s[i];
if(isLeft(cur)) {
checker.push(cur);
} else {
if(!checker.empty() and cur == checker.top()) {
checker.pop();
} else {
return false;
}
}
}
if(checker.empty()) {
return true;
} else {
return false;
}
}
bool isLeft(char& cur) {
switch(cur) {
case '(':
cur = ')';
break;
case '[':
cur = ']';
break;
case '{':
cur = '}';
break;
default:
return false;
}
return true;
}
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment