[LeetCode] 20. Valid Parentheses 合法括号
Given a string containing just the characters '('
, ')'
, '{'
, '}'
, '['
and ']'
, determine if the input string is valid.
An input string is valid if:
- Open brackets must be closed by the same type of brackets.
- 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
输入的字符串只含有'('
, ')'
, '{'
, '}'
, '['
, ']',验证字符串
是否配对合理。
解法:栈Stack,经典的使用栈的题目。遍历字符串,如果为左括号,将其压入栈中,如果遇到为右括号,若此时栈为空,则直接返回false,如不为空,则取出栈顶元素,若为对应的左括号,是合法的继续循环,否则返回false。
Java: Time: O(n), Space: O(n)
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 | public static boolean isValid(String s) { HashMap<Character, Character> map = new HashMap<Character, Character>(); map.put( '(' , ')' ); map.put( '[' , ']' ); map.put( '{' , '}' ); Stack<Character> stack = new Stack<Character>(); for ( int i = 0 ; i < s.length(); i++) { char curr = s.charAt(i); if (map.keySet().contains(curr)) { stack.push(curr); } else if (map.values().contains(curr)) { if (!stack.empty() && map.get(stack.peek()) == curr) { stack.pop(); } else { return false ; } } } return stack.empty(); } |
Java:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 | 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:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 | class Solution: # @return a boolean def isValid( self , s): stack = [] dict = { "]" : "[" , "}" : "{" , ")" : "(" } for char in s: if char in dict .values(): stack.append(char) elif char in dict .keys(): if stack = = [] or dict [char] ! = stack.pop(): return False else : return False return stack = = [] |
Python: Time: O(n), Space: O(n)
1 2 3 4 5 6 7 8 9 | class Solution: def isValid( self , s): stack, lookup = [], { "(" : ")" , "{" : "}" , "[" : "]" } for parenthese in s: if parenthese in lookup: # Cannot use if lookup[parenthese]: KeyError stack.append(parenthese) elif len (stack) = = 0 or lookup[stack.pop()] ! = parenthese: # Cannot use not stack return False return len (stack) = = 0 |
Python: wo
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 | class Solution( object ): def isValid( self , s): """ :type s: str :rtype: bool """ stack = [] m = { '(' : ')' , '[' : ']' , '{' : '}' } n = [ ')' , ']' , '}' ] for i in s: if i in m: stack.append(i) elif i in n and stack: if m[stack.pop()] ! = i: return False else : return False return len (stack) = = 0 |
C++:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 | class Solution { public : bool isValid(string s) { stack< char > parentheses; for ( int i = 0; i < s.size(); ++i) { if (s[i] == '(' || s[i] == '[' || s[i] == '{' ) parentheses.push(s[i]); else { if (parentheses.empty()) return false ; if (s[i] == ')' && parentheses.top() != '(' ) return false ; if (s[i] == ']' && parentheses.top() != '[' ) return false ; if (s[i] == '}' && parentheses.top() != '{' ) return false ; parentheses.pop(); } } return parentheses.empty(); } }; |
类似题目:
[LeetCode] 22. Generate Parentheses
[LeetCode] 32. Longest Valid Parentheses
[LeetCode] 241. Different Ways to Add Parentheses
[LeetCode] 301. Remove Invalid Parentheses
All LeetCode Questions List 题目汇总
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步