首页 > 代码库 > 栈的应用题(1)
栈的应用题(1)
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.
1)stack<char>的数据结构,stk.push(elem),stk.pop(),stk.top等用法。
2)栈为空,输入为左括弧,输入为右括弧,分不同情况讨论,入栈,出栈,退出,continue等
class Solution {
public:bool correct_pair(char elem,char elem2)
{
if(((elem == ‘(‘)&&(elem2 == ‘)‘))||((elem == ‘[‘)&&(elem2 == ‘]‘))||((elem == ‘{‘)&&(elem2 == ‘}‘)))
return true;
else
return false;
}
bool isbegin(char s)
{
if((s == ‘(‘)||(s == ‘{‘)||(s == ‘[‘))
return true;
else
return false;
}
bool is_end(char s)
{
if((s == ‘)‘)||(s == ‘}‘)||(s == ‘]‘))
return true;
else
return false;
}
bool isValid(string s) {
int n = s.size();
stack<char> stk;
if(0 == n)
{
return true;
}
for(int i = 0;i < n;i++)
{
if(0 == stk.size())
{
stk.push(s[i]);
continue;
}
if(isbegin(s[i]))
{
stk.push(s[i]);
}
else if(is_end(s[i]))
{
if(correct_pair(stk.top(),s[i]))
{
stk.pop();
continue;
//s.push(s[i]);
}
else
return false;
}
}
if(0 == stk.size())
return true;
else
return false;
}
};
栈的应用题(1)
声明:以上内容来自用户投稿及互联网公开渠道收集整理发布,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任,若内容有误或涉及侵权可进行投诉: 投诉/举报 工作人员会在5个工作日内联系你,一经查实,本站将立刻删除涉嫌侵权内容。