LeetCode 20 有效的括号
给定一个只包括 ‘(’,’)’,’{’,’}’,’[’,’]’ 的字符串,判断字符串是否有效。
有效字符串需满足:
左括号必须用相同类型的右括号闭合。
左括号必须以正确的顺序闭合。
注意空字符串可被认为是有效字符串。
示例 1:
输入: "()"
输出: true
示例 2:
输入: "()[]{}"
输出: true
示例 3:
输入: "(]"
输出: false
示例 4:
输入: "([)]"
输出: false
示例 5:
输入: "{[]}"
输出: true
解题思路
当我们在遍历时遇见, ‘(’ , ‘[’ , ‘{’ ,要想字符串有效,必须以相同类型的右括号闭合,
因此再遇见 ‘(’ , ‘[’ , ‘{’ ,时,我们将其加入栈中,在遇到其他闭合符号时,要想字符串有效,则栈的顶端必须是与此类型匹配的符号,弹出栈顶端符号,进行比较,不匹配返回False,最后如果栈是空栈,则符号有效,否则无效。
Python3
解法一:
class Solution:
def isValid(self, s: str) -> bool:
stack=[]
for char in s:
if char == ')':
map_string = '('
top_string = stack.pop() if stack else '?'
if top_string != map_string:
return False
elif char == ']':
map_string = '['
top_string = stack.pop() if stack else '?'
if top_string != map_string:
return False
elif char == '}':
map_string = '{'
top_string = stack.pop() if stack else '?'
if top_string != map_string:
return False
else:
stack.append(char)
return not stack
解法一优化
上面的代码过于麻烦,在此做了进一步的简化
class Solution:
def isValid(self, s: str) -> bool:
stack=[]
map = { ')':'(', ']':'[', '}':'{' }
for char in s:
if char in map:
top_string = stack.pop() if stack else '?'
if top_string != map[char]:
return False
else:
stack.append(char)
return not stack
C语言
bool isValid(char * s){
if (s == NULL || s[0] == '\0')
return true;
char stack[5000];
int top = 0;
for (int i = 0; s[i]; ++i)
{
if (s[i] == '(' || s[i] == '[' || s[i] == '{')
stack[top++] = s[i];
else
{
top--;
if (top < 0)
return false;
if (s[i] == ')' && stack[top] != '(' ||
s[i] == ']' && stack[top] != '[' ||
s[i] == '}' && stack[top] != '{' )
return false;
}
}
return (top ? false : true);
}
C++
class Solution {
public:
bool isValid(string s)
{
if (s[0] == '\0')
return true;
char top_element;
stack<char> stack;
for(int i=0;s[i];i++)
{
if (s[i] == '(' || s[i] == '[' || s[i] == '{')
stack.push(s[i]);
else
{
if (stack.empty())
return false;
top_element = stack.top();
if (s[i] == ')' && top_element != '(' ||
s[i] == ']' && top_element != '[' ||
s[i] == '}' && top_element != '{' )
return false;
else
stack.pop();
}
}
return (stack.empty() ? true : false);
}
};