[題解][LeetCode][Valid Parentheses]

題目:

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

The brackets must close in the correct order, "()" and "()[]{}" are all valid but "(]" and "([)]" are not.

題解:

【字符串處理】

用一個List當作堆棧,遇到左括號壓棧,遇到右括號彈棧比較。

最後check一下棧是否爲空即可。


Code:

class Solution:
	# @return a boolean
	def isValid(self, s):
		p = []
		l = ['(','[','{']
		r = [')',']','}']
		for c in s:
			if c in l:
				p.append(c)
			elif c in r:
				if p == []:
					return False
				if p.pop() != l[r.index(c)]:
					return False
		if p == []:
			return True
		else:
			return False


發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章