leetcode:string 20. Valid Parentheses

Given a string containing just the characters '('')''{''}''[' and ']', determine if the input string is valid.

An input string is valid if:

  1. Open brackets must be closed by the same type of brackets.
  2. 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


用一个栈来解决问题,将s字符按顺序入栈,如果为'(' '[' '{' ,则将其入栈,如果为')' '[' '}',若栈顶字符与该字符匹配,如'(' 和 ')' ,则将栈顶元素出栈。若不匹配,则返回False。

扫描二维码关注公众号,回复: 844770 查看本文章

遍历完s中的元素后,如果stack为空,则说明所有字符都匹配,返回True。若不为空,则返回False。

class Solution:
	def isValid(self, s):
		stack = ""
		for i in range(0,len(s)):
			c = s[i]
			if (c=='(' or c=='[' or c=='{'):
				stack += c
			elif len(stack)==0:
				return False
			elif c==')':
				if stack[-1]!='(':
					return False
				else:
					stack = stack[:-1]
			elif c==']':
				if stack[-1]!='[':
					return False
				else:
					stack = stack[:-1]
			elif c=='}':
				if stack[-1]!='{':
					return False
				else:
					stack = stack[:-1]
		if(len(stack)==0):
			return True
		else:
			return False

猜你喜欢

转载自blog.csdn.net/w16337231/article/details/80159918
今日推荐