Given a string containing just the characters ‘(’, ‘)’, ‘{’, ‘}’, ‘[’ and ‘]’, determine if the input string is valid.
An input string is valid if:
Open brackets must be closed by the same type of brackets.
Open brackets must be closed in the correct order.
Note that an empty string is also considered valid.
Example 1:
Input: “()”
Output: true
Example 2:
Input: “()[]{}”
Output: true
Example 3:
Input: “(]”
Output: false
Example 4:
Input: “([)]”
Output: false
Example 5:
Input: “{[]}”
Output: true
翻译
给定一个只包括 ‘(’,’)’,’{’,’}’,’[’,’]’ 的字符串,判断字符串是否有效。
有效字符串需满足:
左括号必须用相同类型的右括号闭合。
左括号必须以正确的顺序闭合。
注意空字符串可被认为是有效字符串。
示例 1:
输入: “()”
输出: true
示例 2:
输入: “()[]{}”
输出: true
示例 3:
输入: “(]”
输出: false
示例 4:
输入: “([)]”
输出: false
示例 5:
输入: “{[]}”
输出: true
分析
用栈的数据结构来存储括号就很容易了。左括号就入栈,有括号就出栈。字符串遍历结束时如果刚好栈空,说明匹配。
c++实现
class Solution {
public:
bool isValid(string s) {
stack<char> kuohao;
bool pipei = true;
if (s == "")
return pipei;
for (int i = 0; i < s.length(); i++)
{
if (s[i] == '(' || s[i] == '{' || s[i] == '[')
kuohao.push(s[i]);
else
{
if (!kuohao.empty())
{
if (s[i] == ')' && kuohao.top() == '(')
{
kuohao.pop();
continue;
}
else if (s[i] == ']' && kuohao.top() == '[')
{
kuohao.pop();
continue;
}
else if (s[i] == '}' && kuohao.top() == '{')
{
kuohao.pop();
continue;
}
else
{
pipei = false;
break;
}
}
else
{
pipei = false;
break;
}
}
}
if (pipei == true && !kuohao.empty() == 1)
pipei = false;
return pipei;
}
};