给出一个仅包含字符'(',')','{','}','['和']',的字符串,判断给出的字符串是否是合法的括号序列
括号必须以正确的顺序关闭,"()"和"()[]{}"都是合法的括号序列,但"(]"和"([)]"不合法。
括号必须以正确的顺序关闭,"()"和"()[]{}"都是合法的括号序列,但"(]"和"([)]"不合法。
数据范围:字符串长度
要求:空间复杂度 ,时间复杂度
def isValid(self , s: str): d_type_1 = [] dict_1 = {'{':'}','[':']','(':')'} for i in s: if i in ['(','[','{']: d_type_1.append(i) if i in [')',']','}']: if len(d_type_1) != 0 and dict_1[d_type_1[-1]] == i: d_type_1.pop(-1) else: return False if len(d_type_1) == 0: return True else: return False
class Solution:
def isValid(self , s: str) -> bool: # write code here n = len(s) stack = [] left = "({[" right = ")}]" if(s and n%2 == 0 and s[0] in left): for i in s: if(i in left): stack.append(i) else: if(i == ')' and stack[-1] == '('): stack.pop() elif(i == '}' and stack[-1] == '{'): stack.pop() elif(i == ']' and stack[-1] == '['): stack.pop() else: return False if stack: return False else: return True else: return False
# 使用一个栈,左括号直接入栈,右括号判断和栈顶是否匹配,匹配则弹出栈顶,最后空栈则有效。 class Solution: def isValid(self, s: str) -> bool: # write code here stack = [] left = "([{" right = ")]}" for i in s: if i in left: stack.append(i) elif i in right: if stack and stack[-1] in left and left.index(stack[-1]) == right.index(i): stack.pop() else: return False if not stack: return True else: return False
# # 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可 # # # @param s string字符串 # @return bool布尔型 # class Solution: def isValid(self, s: str) -> bool: # write code here # 辅助栈 st = [] for i in range(len(s)): if len(st) == 0: st.append(s[i]) elif ( (st[-1] == "{" and s[i] == "}") &nbs***bsp;(st[-1] == "[" and s[i] == "]") &nbs***bsp;(st[-1] == "(" and s[i] == ")") ): st.pop() else: st.append(s[i]) return False if len(st)!=0 else True
class Solution: def isValid(self , string: str) -> bool: # write code here class Stack: def __init__(self): self.items=[] def isEmpty(self): return self.items == [] def push(self,item): self.items.append(item) def pop(self): return self.items.pop() def size(self): return len(self.items) def match(open,close): opens='([{' closes=')]}' if opens.index(open) == closes.index(close): return True else: return False s=Stack() balanced=True index=0 while index<len(string) and balanced: char=string[index] if char in '([{': s.push(char) else: if s.isEmpty(): balanced=False #右括号开头,无效 else: top=s.pop() if not match(top,char): balanced=False index=index+1 if balanced and s.isEmpty(): return True else: return False
class Solution: def isValid(self , s: str) -> bool: stack = [] if len(s) % 2 != 0: return False for i in s: # print(stack) if i in ("[", '{', "("): stack.append(i) continue elif i in ("}", ')', "]"): if stack == []: return False if i == ")" and stack.pop() == "(": continue elif i == "}" and stack.pop() == "{": continue elif i == "]" and stack.pop() == "[": continue else: return False return len(stack) == 0
class Solution: def isValid(self , s: str) -> bool: # write code here if len(s) % 2 != 0:#如果长度不是偶数,直接false return False elif s[0] == ')'&nbs***bsp;s[0] == ']'&nbs***bsp;s[0] == '}':#如果第一个元素为右括号,则false return False else:#当第一个元素是左括号,判断后续元素能否一一配对 stack = [] for i in s: if i == '('&nbs***bsp;i == '['&nbs***bsp;i == '{':#所有左括号入栈 stack.append(i) else:#当遍历到右括号时 if i == ')' and stack[-1]!='(':#如果列表最后一位不是能与之配对的左括号,false return False elif i == ']' and stack[-1]!='[': return False elif i == '}' and stack[-1]!='{': return False else:#是能配对的,就pop stack.pop() if stack:#如果最后列表中还有元素,则false return False else: return True
# # 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可 # # # @param s string字符串 # @return bool布尔型 # class Solution: def isValid(self , s: str) -> bool: # write code here stack = [] # 用于存储左括号 mapping = {')': '(', '}': '{', ']': '['} # 定义括号对应关系 for char in s: if char in mapping: # 若当前字符为右括号 if not stack&nbs***bsp;stack[-1] != mapping[char]: return False # 若栈为空或栈顶元素与当前右括号不匹配,则返回False stack.pop() # 匹配成功,弹出栈顶的左括号 else: stack.append(char) # 若当前字符为左括号,压入栈中 return not stack # 若栈为空,则表示所有括号都已匹配完全,返回True,否则返回False
# 解法一 class Solution: def isValid(self, s: str) -> bool: # 循环替换,直到字符串为空或者不变 while True: ori = s s = s.replace("()", "").replace("{}", "").replace("[]", "") # 如果字符串为空,则为True if not s: return True # 如果字符串不再发生变化,则为False if s == ori: return False # 解法二 class Solution: def isValid(self, s: str) -> bool: # 定义一个映射关系 def judge_duichen(s1, s2): mapping = {"}": "{", ")": "(", "]": "["} return True if s2 in mapping and mapping[s2] == s1 else False # 定义一个列表,用来存储当前入栈的元素 all = [] for i in s: # 如果当前栈为空,则将当前元素入栈,并且跳到下一次循环 if not all: all = [i] continue # 如果当前元素与栈顶元素对称,则将栈顶元素出栈 if judge_duichen(all[-1], i): all.pop() # 如果不对称,则将当前元素入栈 else: all.append(i) # 如果栈为空,则为True,否则为False return all == [] # 解法三: class Solution: def isValid(self, s: str) -> bool: all = [] mapping = {"}": "{", ")": "(", "]": "["} # 先让所有的左括号入栈 for i in s: if i in "{[(": all.append(i) # 如果当前元素是右括号,且栈为空,则返回False,因为右括号不能先于左括号出现 elif all == []: return False # 如果当前元素是右括号,则判断栈顶元素是否与其对称,如果对称,则将栈顶元素出栈,否则返回False elif mapping[i] == all[-1]: all.pop() else: return False # 在循环结束后,如果栈为空,则为True,否则为False return all == []
class Solution: def isValid(self , s: str) -> bool: # write code here if len(s)%2 == 1: return False else: stack = [] # 左括号入栈,右括号没必要入栈,入了后续也不可能匹配上 pairs = ["()","[]","{}"] for i in range(len(s)): if s[i] in "({[": stack.append(s[i]) else: #输入的是右括号 if len(stack) == 0: return False # 栈里没有左括号和右括号匹配 else: pair = stack[-1]+s[i] if pair in pairs: stack.pop(-1) # 匹配成功则弹出栈里的最后一个左括号 else: return False # 如果栈里最后一个左括号和右括号不匹配则永远不会匹配上了 if len(stack) == 0: # 判断所有左括号是否全部出栈 return True else: return False
class Solution: def isValid(self , s: str) -> bool: # write code here if not s: return True if s[0] == ')'&nbs***bsp;s[0] == ']'&nbs***bsp;s[0] == '}': return False if len(s) % 2 == 1: return False ss = [] for i in s: if i == '('&nbs***bsp;i == '['&nbs***bsp;i == '{': ss.append(i) else: if not ss: return False p = ss.pop() if (i == ')' and p == '(')&nbs***bsp;(i == ']' and p == '[')&nbs***bsp;(i == '}' and p == '{'): flag = 1 else: return False if ss: return False return Trueeasy
class Solution: def isValid(self , s ): # write code here # 栈原理 result = [] try : for i in s : if i == '['&nbs***bsp;i == '('&nbs***bsp;i == '{' : result.append(i) print(result) elif i == ']' and result[-1] == '[' : result.pop() elif i == ')' and result[-1] == '(' : result.pop() elif i == '}' and result[-1] == '{' : result.pop() except : return False if result == [] : return True else : return False