LeetCode--No.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.

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
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值