Description:
Given a string containing just the characters '('
, ')'
, '{'
, '}'
, '['
and ']'
, determine if the input string is valid.
Note:
The brackets must close in the correct order, "()"
and "()[]{}"
are all valid but "(]"
and "([)]"
are not.
Solution:
Analysis and Thinking:
题目要去对于输入的字符串,其中包含‘{‘ ’}’、‘(‘ ’)’等闭合字符,判断字符串是否合法。合法的标准当然是要以正确的顺序闭合。这是一个明显的栈应用问题,利用stack就可以解决,例如遇到左闭合符号入栈,如果遇到了一个右闭合符号,弹出一个左闭合符号,看是否匹配,因为闭合符号遵循最近匹配原则,因此扫描一遍字符串,就可以得出结果。
Steps:
1.遍历字符串中每一个字符
2.若当前字符与栈顶匹配,则出栈
3.否则,将当前遍历元素入栈
Codes:
class Solution {
public:
bool isValid(string s) {
if(s.length() == 0) //空字符串,合法
{
return true;
}
stack<char> record; //用于记录字符串的栈
record.push(s[0]);
for(int i = 2; i < s.length(); i++)
{
if(!record.empty() && isValid_helper(record.top(), s[i])) //判断是否有闭合符号匹配,若有,则出栈,否则将字符入栈
{
record.pop();
}
else
{
record.push(s[i]);
}
}
if(record.empty()) //判断的标准就是,是否所有的闭合符号都被匹配
{
return true;
}
else
{
return false;
}
}
bool isValid_helper(char a, char b) //用于辅助判断闭合符号是否匹配
{
switch(a)
{
case '(':
if (b==')')
return true;
break;
case '{':
if (b=='}')
return true;
break;
case '[':
if (b==']')
return true;
break;
default:
return false;
}
}
};
Results: