問題:給定一個字符串所表示的括號序列,包含以下字符: '(', ')', '{', '}', '[' and ']', 判定是否是有效的括號序列
如括號必須依照 "()" 順序表示, "()[]{}" 是有效的括號,但 "([)]"則是無效的括號。
思路: 括號最重要的是匹配,只要出現(xiàn)()[]{},就可以抵消掉,否則就false,而且對于stack的第一個元素 不能是}]),其他的就可以push入棧。
這里,我們用數(shù)組來模擬stack,string作為輸入源。
注意匹配的順序,不能是“)(”。
Python3
class Solution:
# @param {string} s A string
# @return {boolean} whether the string is a valid parentheses
def isValidParentheses(self, s):
# Write your code here
stack = []
for index in s:
if index == "(" or index == "{" or index == "[":
stack.append(index)
continue
length = len(stack)
if stack:
if index == ")" and stack[length - 1] == "(":
stack.pop()
continue
if index == "}" and stack[length - 1] == "{":
stack.pop()
continue
if index == "]" and stack[length - 1] == "[":
stack.pop()
continue
else:
return False
else:
if index == "}" or index == "]" or index == ")":
return False
if stack:
return False
else:
return True
這里,我有遇到一個問題,如何判斷一個數(shù)組為空。
stack == None 是行不通的。
親測以下均可:
a = []
if not bool(a):
if not a:
if len(a) == 0:
if a == []:
也就是說,一個空的列表 == 0 == False
java
public class Solution {
/**
* @param s A string
* @return whether the string is a valid parentheses
*/
public boolean isValidParentheses(String s) {
// Write your code here
Stack<Character> stack = new Stack<Character>();
for (char bracket: s.toCharArray())
{
if (bracket == '(')
{
stack.push(')');
}
else if (bracket == '{')
{
stack.push('}');
}
else if (bracket == '[')
{
stack.push (']');
}
else if (stack.isEmpty() || bracket != stack.pop())
{
return false;
}
}
return stack.isEmpty();
}
}
在用java做的時候,我發(fā)現(xiàn)了一個好方法,就是如上思路,簡潔可行。
也發(fā)現(xiàn)了幾個問題:
- java中 “{” 和 ‘{’ 是不一樣的類型:第一個是string 第二個是 char。
- java中有現(xiàn)成的stack,c++也有,反而就是python沒有。但是他們建立順序棧的方式都差不多,均用了數(shù)組。
下面就是相關的信息:
Java 數(shù)據(jù)結構包括: 枚舉(Enumeration)位集合(BitSet)向量(Vector)棧(Stack)字典(Dictionary)哈希表(Hashtable)屬性(Properties)
Python3數(shù)據(jù)結構包括:列表(棧,隊列)集合,字典,元組