LeetCode 20. Valid Parentheses---Java

题目:

Given a string containing just the characters ‘(’, ‘)’, ‘{’, ‘}’, ‘[’ and ‘]’, determine if the input string is valid.

An input string is valid if:
Open brackets must be closed by the same type of brackets.
Open brackets must be closed in the correct order.
Note that an empty string is also considered valid.

Example 1:
Input: “()”
Output: true

Example 2:
Input: “()[]{}”
Output: true

Example 3:
Input: “(]”
Output: false

Example 4:
Input: “([)]”
Output: false

Example 5:
Input: “{[]}”
Output: true

解答:

首先确定本题的思路为:使用栈
自己一开始的解题思路为:使用栈的数据结构,因为匹配的括号的话,一定是成对出现的,若将左括号一次压入栈,遇到匹配的右括号在弹出栈,则若是匹配的话,栈最后一定为空。
stack.push();向栈中添加数据
stack.peek();栈的顶部的数据

class Solution{
    public static boolean isValid(String s){
        if(s.length()==0){
            return true;
        }
        Stack<Character> stack=new Stack<>();
        for(int i=0;i<s.length();i++){
            char c=s.charAt(i);
            if(c=='('||c=='{'||c=='['){
                stack.push(c);
            }else if(stack.isEmpty()){
                return false;
            }else if((stack.peek()=='('&&c==')')||(stack.peek()=='{'&&c=='}')||(stack.peek()=='['&&c==']')){
                stack.pop();
            }else{
                return false;
            }
        }
        return stack.isEmpty();
    }
}

后来发现了更为简便的解法:
思路为:
当碰到左括号,则压入栈的是右括号,在遇到右括号时,弹出栈,判断是否弹出的栈顶元素就是当前扫描的右括号,若不是,则不是匹配的字串,返回false,最后遍历完成后,判断栈是否为空。

class Solution {
    public static boolean isValid(String s) {
		if (s.isEmpty())
            return true;
        Stack<Character> stack = new Stack<>();
        for (char c : s.toCharArray()) {
            if (c == '(')
                stack.push(')');
            else if (c == '{')
                stack.push('}');
            else if (c == '[')
                stack.push(']');
            else if (stack.isEmpty() || stack.pop() != c)
                return false;
        }
        return stack.isEmpty();
    }
}

另有解法:

class Solution {
    public boolean isValid(String s) {
        Stack<Character> stack=new Stack<Character>();
        for(int i=0;i<s.length();i++){
        	char c=s.charAt(i);
            if(stack.isEmpty()){
            	stack.push(c);
            }else{
            	if(stack.peek()-c==-1||stack.peek()-c==-2){
            		stack.pop();
            	}else{
            		stack.push(c);
            	}
            }
        }
        System.out.println(stack.size());
        return stack.isEmpty();
    }
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值