Problem:Given a string containing just the characters '(', ')', '{', '}', '[' and ']', determine if the input string is valid.
Solution:采用stack,当字符为上括号时push进stack,否之则从stack pop出字符看是否匹配。(注意一些特殊情况)
class Solution {
public:
/**
* @param s A string
* @return whether the string is a valid parentheses
*/
//'(', ')', '{', '}', '[' and ']'
bool isValidParentheses(string& s) {
// Write your code here
int stringLength=s.length();
stack<string> check;
for(int i=0;i<stringLength;i++){
if(s.substr(i,1)=="("||s.substr(i,1)=="{"||s.substr(i,1)=="[")
check.push(s.substr(i,1));
else if(!check.empty()&&((s.substr(i,1)==")"&&check.top()!="(")||(s.substr(i,1)=="]"&&check.top()!="[")
||(s.substr(i,1)=="}"&&check.top()!="{")))
return 0;
else if(check.empty())
return 0;
else
check.pop();
}
if(!check.empty())
return 0;
return 1;
}
};