问题
https://leetcode.com/problems/valid-parentheses/
解法一(2ms)
使用c++ stack实现
class Solution {
public:
bool isValid(string s) {
stack<char> st;
for (int i=0; i< s.size(); i++)
{
char c;
if (s[i] =='(' || s[i] == '{' || s[i]=='[')
st.push(s[i]);
else if (s[i] == ')')
{
if (st.empty() || st.top() != '(')
return false;
st.pop();
}else if (s[i] == '}')
{
if (st.empty() || st.top() != '{')
return false;
st.pop();
}else if (s[i] == ']')
{
if (st.empty() || st.top() != '[')
return false;
st.pop();
}
}
return st.empty();
}
};
解法二 (0ms)
自己维护堆栈
class Solution {
public:
bool isValid(string s) {
char st[s.size()];
int stPtr = -1;
for (int i=0; i< s.size(); i++)
{
char c;
if (s[i] =='(' || s[i] == '{' || s[i]=='[')
st[++stPtr] = s[i];
else if (s[i] == ')')
{
if (stPtr==-1 || st[stPtr] != '(')
return false;
stPtr--;
}else if (s[i] == '}')
{
if (stPtr==-1 || st[stPtr] != '{')
return false;
stPtr--;
}else if (s[i] == ']')
{
if (stPtr==-1 || st[stPtr] != '[')
return false;
stPtr--;
}
}
return stPtr==-1;
}
};
本文介绍两种使用C++实现的解决方案,一种利用内置的stack容器,另一种自行维护堆栈,来验证字符串中括号是否正确匹配。通过遍历字符串并使用堆栈数据结构,判断每个字符是否与前一个括号闭合,最终确定字符串中的括号是否完全匹配。
927

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



