LeetCode-20/220316


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に戻ります.