LeetCode-20/220316
1472 ワード
https://leetcode.com/problems/valid-parentheses/
Python
class Solution:
def isValid(self, s: str) -> bool:
st = []
dict = {"]":"[", "}":"{", ")":"("}
for x in s:
if x in dict.values():
st.append(x)
elif x in dict.keys():
if st == [] or dict[x] != st.pop():
return False
else:
return False
return st == []
Java
public boolean isValid(String s) {
Stack<Character> stack = new Stack<Character>();
for (char c : s.toCharArray()) {
if (c == '(')
stack.push(')');
else if (c == '{')
stack.push('}');
else if (c == '[')
stack.push(']');
else if (stack.isEmpty() || stack.pop() != c)
return false;
}
return stack.isEmpty();
}
Pythonと同様にスタック内のpush,popを用いて解決する.一致する括弧を削除し、空のリストだけを残してTrueに戻ります.Reference
この問題について(LeetCode-20/220316), 我々は、より多くの情報をここで見つけました https://velog.io/@iyong829/LeetCode-20-220316テキストは自由に共有またはコピーできます。ただし、このドキュメントのURLは参考URLとして残しておいてください。
Collection and Share based on the CC Protocol