题目:
All input strings will be nonempty, and will only consist of parentheses, brackets and curly braces: ()[]{}
.
What is considered Valid?
A string of braces is considered valid if all braces are matched with the correct brace.
Examples
"(){}[]" => True
"([{}])" => True
"(}" => False
"[(])" => False
"[({})](]" => False
思路:
使用栈来存储字符,
- 当字符为
({[
时,入栈 - 当字符为
)
时,判断栈是否为空,若为空,返回false
,若不为空,接着判断栈顶元素是否为(
,如果是,则弹出栈顶元素,若不是返回false
- 当字符为
}
时,判断栈是否为空,若为空,返回false
,若不为空,接着判断栈顶元素是否为{
,如果是,则弹出栈顶元素,若不是返回false
- 当字符为
]
时,判断栈是否为空,若为空,返回false
,若不为空,接着判断栈顶元素是否为[
,如果是,则弹出栈顶元素,若不是返回false
- 字符串遍历结束,判断栈是否为空,若为空,则返回
true
,否则,返回false
代码:
bool valid_braces(std::string braces)
{
// valid or not valid?
std::stack<char> s;
for(int i=0;i<braces.length();i++)
{
if(braces[i]=='('||braces[i]=='['||braces[i]=='{'){
s.push(braces[i]);
}else if(braces[i]==')'){
if(!s.empty()&&s.top()=='(')
{
s.pop();
}else{
return false;
}
}else if(braces[i]==']'){
if(!s.empty()&&s.top()=='[')
{
s.pop();
}else{
return false;
}
}else if(braces[i]=='}')
{
if(!s.empty()&&s.top()=='{')
{
s.pop();
}else{
return false;
}
}
}
if(!s.empty())
{
return false;
}
return true;
}
小tips:
- 创建栈:
stack<char> s
- 向栈中插入元素:
s.push(braces[i]);
- 弹栈:
s.pop()
- 返回栈顶元素:
s.top()