题目描述:
给定一个只包括 '('
,')'
,'{'
,'}'
,'['
,']'
的字符串,判断字符串是否有效。
有效字符串需满足:
- 左括号必须用相同类型的右括号闭合。
- 左括号必须以正确的顺序闭合。
注意空字符串可被认为是有效字符串。
示例:
示例 1:
输入: "()" 输出: true
示例 2:
输入: "()[]{}" 输出: true
示例 3:
输入: "(]" 输出: false
示例 4:
输入: "([)]" 输出: false
示例 5:
扫描二维码关注公众号,回复:
4112171 查看本文章
输入: "{[]}" 输出: true
我提交的代码:
class Solution {
public:
int singleCharToInt(char a)
{
switch(a)
{
case '(':
return 1;
case ')':
return 6;
case '[':
return 5;
case ']':
return 2;
case '{':
return 3;
case '}':
return 4;
default:
return 0;
}
}
bool isValid(string s)
{
int s_length = s.size();
if(s_length == 0)
{
return true;
}
if(s_length%2 != 0)
{
return false;
}
stack<int> stk;
int i;
int pre = singleCharToInt(s[0]);
int current;
if(pre % 2 == 0)
{
return false;
}
else
{
stk.push(pre);
}
for (i = 1; i < s_length; ++i)
{
current = singleCharToInt(s[i]);
if(current % 2 == 0)
{
if(pre + current == 7)
{
stk.pop();
if(stk.empty())
{
return true;
}
pre = stk.top();
}
else
{
return false;
}
}
else
{
stk.push(current);
pre = current;
}
}
if(stk.empty())
{
return true;
}
else
{
return false;
}
}
};
执行用时: 4 ms, 在Valid Parentheses的C++提交中击败了70.92% 的用户