Leet Code 20 Valid Parentheses
来源:互联网 发布:gta5没网络怎么玩单机 编辑:程序博客网 时间:2024/06/11 01:15
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.
【算法思路】
用栈。
public boolean isValid(String s) {int length = s.length();if(length % 2 == 1){return false;}HashMap<Character, Character> map = new HashMap<Character, Character>();map.put('(', ')');map.put('{', '}');map.put('[', ']');Stack<Character> stack = new Stack<Character>();if(map.containsKey(s.charAt(0))) stack.push(s.charAt(0)); else return false;for(int i = 1; i < length; i ++){char ch = s.charAt(i);if(!stack.isEmpty() && (map.get(stack.peek()) == ch)){stack.pop();}else if(map.containsKey(ch))stack.push(ch);else return false;if(!stack.isEmpty() && (stack.size() > length - i))return false;}return stack.isEmpty();}
0 0
- Leet Code 20 Valid Parentheses
- [leet code] Valid Parentheses
- Leet Code OJ 20. Valid Parentheses [Difficulty: Easy]
- Leet Code OJ 20. Valid Parentheses [Difficulty: Easy]
- [leet code] Generate Parentheses
- [leet code] Valid Sudoku
- Leet Code OJ: Valid Number
- CODE 111: Valid Parentheses
- 【Leet Code】 242. Valid Anagram--easy
- CODE 101: Longest Valid Parentheses
- Leet Code OJ 242. Valid Anagram [Difficulty: Easy]
- Leet Code OJ 125. Valid Palindrome [Difficulty: Easy]
- leetcode 日经贴,python code -Valid Parentheses
- leetcode 日经贴,python code -Longest Valid Parentheses
- leetcode 日经贴,Cpp code -Valid Parentheses
- LeetCode 20: Valid Parentheses
- LeetCode(20) Valid Parentheses
- leetcode 20 Valid Parentheses
- 【小熊刷题】3Sum Closest <Leetcode 16, Java>
- Leet Code Medium 18 4Sum
- Leet Code 19 Remove Nth Node From End of List
- 常见安卓主题显示
- LeetCode Triangle
- Leet Code 20 Valid Parentheses
- 【工作感悟】——聊聊面试那些事
- 【小熊刷题】Letter Combinations of a Phone Number <Leetcode 17, Java>
- extern 与 define 区别
- 【小熊刷题】Remove Nth Node From End of List <Leetcode 19, Java>
- Ember.js 入门指南——handlebars基础
- combination sum II
- Leetcode: Count Univalue Subtrees
- [LeetCode] Invert Binary Tree - 二叉树翻转系列问题