您的位置:首页 > 其它

LeetCode 20. Valid Parentheses

2017-04-10 15:16 405 查看
题目描述:

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) {
stack<char> a;//用来进行处理的char型栈
int len = s.length();//计算s的长度
for (int i = 0; i < len; ++i){//从第一个开始遍历字符串s
if (a.size() == 0){//如果栈a没有元素
a.push(s[i]);//将当前的s[i]放入a,继续循环下一个元素
continue;
}
if (a.top() == '('){//如果当前栈a的顶为'('
if (s[i] == ')'){//如果当前的s[i]为')',即与题中要求匹配
a.pop();//将栈a顶弹出
}
else{//否则将当前s[i]放入a
a.push(s[i]);
}
}
else if (a.top() == '['){//如果当前栈a的顶为'['同理
if (s[i] == ']'){
a.pop();
}
else{
a.push(s[i]);
}
}
else if (a.top() == '{'){//如果当前栈a的顶为'{'同理
if (s[i] == '}'){
a.pop();
}
else{
a.push(s[i]);
}
}
}
return bool(!a.size());//返回bool(!a.size),如果最终a的size为0,则满足;否则不满足
}
};


输出结果: 3ms
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: