Valid Parentheses
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.
解题思路:
一个简单的字符匹配问题,安装题目的要求很快可以写出程序。
Code:
class Solution {
public:
bool isValid(string s) {
stack<char> st;
for(int i=0;i<s.size();i++)
{
if(s[i]==')' || s[i]==']' || s[i]=='}')
{
if(st.empty())
return false;
else
{
char ch=st.top();
st.pop();
if((ch=='('&&s[i]!=')') ||(ch=='[' && s[i]!=']') || (ch=='{' && s[i]!='}'))
return false;
}
}
else
st.push(s[i]);
}
return st.empty();
}
};
本文介绍了一个简单的字符匹配问题——括号验证。通过遍历输入字符串并利用栈来判断括号是否正确配对,实现了有效括号字符串的验证算法。
218

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



