LeetCode--No.20--Valid Parentheses

来源:互联网 发布:星际淘宝网笔下 编辑:程序博客网 时间:2024/05/17 07:05

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.

Subscribe to see which companies asked this question

注意:
1. HashMap 声明时可以注明格式
2. String 可以求长度。String.length()
3. String 可以去某一个值作为Char s.charAt(i)
4. Stack的使用

代码转载自:http://www.programcreek.com/2012/12/leetcode-valid-parentheses-java/   侵删

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();    }}

按照自己的思路重新写了一下,但是借鉴了一些上面的java语法:

public class Solution {    public boolean isValid(String s) {        HashMap<Character, Integer> map = new HashMap<Character, Integer>();        map.put('(',1);        map.put('[',2);        map.put('{',3);        map.put(')',-1);        map.put(']',-2);        map.put('}',-3);        Stack<Integer> stack = new Stack<Integer>();        for(int i = 0; i < s.length(); i++){            char curr = s.charAt(i);            int temp = map.get(curr);            if(temp > 0){                stack.push(temp);            }            else{                if (!stack.empty() && (stack.peek() + temp == 0))                    stack.pop();                else                    return false;            }        }        return stack.empty();    }}

这里要注意的是: 记得判断 stack.empty()

不然直接取stack.peek()会报错

0 0
原创粉丝点击