LeetCode-20 Valid Parentheses(判断括号是否规范)
2015-04-25 11:55
579 查看
LeetCode-20 Valid Parentheses
Given a string containing just the characters
determine if the input string is valid.
The brackets must close in the correct order,
all valid but
not.
我的代码:
Runtime: 245 ms
分析:用链表存储,每次存完一个判断是左边括号还是右边括号。左边括号则直接添加在链表末尾,右边括号则判断链表末尾的是否有符合的左括号与其对应,有的话移除链表末尾的括号,继续往下......一旦发现不对应,则判断为假~~~~。最后循环结束后,判断链表是否为空,为空说明所以括号刚好消除,不为空说明有多余的左括号,即返回假。
别人的代码:
Runtime: 321 ms
发现别人和自己写的是一样的想法,别人用的是Stack来存储,
我也觉得确实用栈来存储是比较好的。毕竟linkedlist底层是双向链表,而这里不需要用到。
(运行速度可能和LeetCode服务器的状态也有关吧。)
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 class Solution { public boolean isValid(String s) { HashMap<Character, Character> map = new HashMap<Character, Character>(); map.put(')', '('); map.put(']', '['); map.put('}', '{'); LinkedList<Character> save = new LinkedList<>(); if (s.equals("")) { return true; } for (int i = 0; i < s.length(); i++) { if (s.charAt(i) !=')' && s.charAt(i)!=']' && s.charAt(i)!='}' ) { save.add(s.charAt(i)); }else { if ( !save.isEmpty() && save.peekLast() == map.get(s.charAt(i)) ) { save.pollLast(); }else { return false; } } } return save.isEmpty(); } }
Runtime: 245 ms
分析:用链表存储,每次存完一个判断是左边括号还是右边括号。左边括号则直接添加在链表末尾,右边括号则判断链表末尾的是否有符合的左括号与其对应,有的话移除链表末尾的括号,继续往下......一旦发现不对应,则判断为假~~~~。最后循环结束后,判断链表是否为空,为空说明所以括号刚好消除,不为空说明有多余的左括号,即返回假。
别人的代码:
public class Solution { public 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(); } }
Runtime: 321 ms
发现别人和自己写的是一样的想法,别人用的是Stack来存储,
我也觉得确实用栈来存储是比较好的。毕竟linkedlist底层是双向链表,而这里不需要用到。
(运行速度可能和LeetCode服务器的状态也有关吧。)
相关文章推荐
- LeetCode 20 Valid Parentheses(用栈判断括号匹配)
- Leetcode 20 Valid Parentheses 判断括号匹配
- LeetCode 20. Valid Parentheses--验证括号是否有效
- LeetCode 20. Valid Parentheses 判断()[]{}是否完整
- LeetCode Valid Parentheses(判断括号是否匹配)
- LeetCode Valid Parentheses判断括号是否配对
- leetcode20 Valid Parentheses 有效的括号
- leetCode 20.Valid Parentheses (有效的括号) 解题思路和方法
- 【Codewars】判断括号是否有效 validParentheses
- leetcode 20 Valid Parentheses 括号匹配
- LeetCode20——Valid Parentheses(括号匹配问题,使用栈的知识)
- LeetCode 20 Valid Parentheses 括号匹配问题
- LeetCode 20. Valid Parentheses(括号校验)
- leetcode 20 Valid Parentheses 括号匹配
- LeetCodet题解--20. Valid Parentheses(括号匹配问题)
- LeetCode 20 Valid Parentheses(括号匹配)
- Valid Parentheses 判断括号组合是否有效@LeetCode
- LeetCode 20 Valid Parentheses (括号匹配问题)
- LeetCode 20. Valid Parentheses(合法括号序列)
- [LeetCode] 20. Valid Parentheses 合法括号