Created
February 12, 2013 18:54
-
-
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.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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