leetcode20. Valid Parentheses
思路:
做一个栈,遇到对称的符号则出栈,否则入栈,最后判断栈是否为空。
class Solution {
public:
bool isValid(string s) {
string stack(s);
int top = -1;
if(s.size()<=0)
return true;
for(int i=0;i<s.size();i++){
switch(s[i]){
case '(':
case '{':
case '[':
stack[++top] = s[i];
break;
case ')':
if(top<0 || stack[top]!='(') return false;
top--;
break;
case '}':
if(top<0 || stack[top]!='{') return false;
top--;
break;
case ']':
if(top<0 || stack[top]!='[') return false;
top--;
break;
default:
return false;
}
}
if(top==-1) return true;
else return false;
}
};
本文介绍了一种使用栈来验证括号序列有效性的方法。通过遍历输入字符串,遇到开括号将其压入栈中,遇到闭括号时检查栈顶元素是否匹配。最终栈为空则序列有效。
270

被折叠的 条评论
为什么被折叠?



