您的位置:首页 > 其它

LeetCode-20 Valid Parentheses(判断括号是否规范)

2015-04-25 11:55 579 查看
LeetCode-20 Valid Parentheses

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服务器的状态也有关吧。)

内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: