class Solution {
public:
/**
*
* @param s string字符串
* @return bool布尔型
*/
bool isValid(string s) {
// write code here
int num = s.length();
if(num % 2 != 0)
return false;
stack<char> S;
char tmp;
for(int i = 0; i < num; i++){
if(s[i] == '(' || s[i] == '{' || s[i] == '['){
S.push(s[i]);
continue;
}
if(S.empty()) return false;
switch(s[i]){
case ')':
tmp = S.top();
S.pop();
if(tmp != '(')
return false;
break;
case '}':
tmp = S.top();
S.pop();
if(tmp != '{')
return false;
break;
case ']':
tmp = S.top();
S.pop();
if(tmp != '[')
return false;
break;
default:
return false;
}
}
if(!S.empty()) return false;
return true;
}
};
思路:遍历字符串,遇到左括号就入栈,遇到右括号时,先判断栈是否为空(栈空的话说明没有左括号与之配对),非空的话再看栈顶元素是否与之匹配。遍历结束后若栈非空,则说明有左括号没有完成配对。