leetcode: Valid Parentheses - two kinds of solutions using Java

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

An input string is valid if:

  1. Open brackets must be closed by the same type of brackets.
  2. Open brackets must be closed in the correct order.

Note that an empty string is also considered valid.


从前到后遍历字符串中的字符,如果该字符是左括号('(','[','{')就依次存储;如果是右括号(')',']','}')就要与已保存的最近一次的字符进行比对,如果是同类型的括号(配成了一对),将其弹出,不再存储;如果既不是左括号又不是右括号,报错。遍历完字符串中的字符后,存储的字符数为空,返回true,否则false。

给出2种java solutions:  使用Stack(java.util.Stack),后进先出(last in first out)的堆栈

1. clearly understandable solution (a bit faster than the following one)

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(c == '(' || c== '[' || c== '{'){
                stack.push(c);
            }
            else if(!stack.empty() && ((c == ')' && stack.peek() == '(') ||( c == ']' && stack.peek() == '[' ) || ( c == '}' && stack.peek() == '{'))){
                stack.pop();  //before pop operation,test if the stack is empty or not is needed              
            }else{
                return false;
            }
        }
        return stack.empty();
    }
}

2. a tricky solution, but a little slower:

class Solution {
    public boolean isValid(String s) {
        Stack<Character> stack = new Stack<>();
        for(char c:s.toCharArray()){//nice short for loop
            if(c == '('){
                stack.push(')'); //once got the left bracket, just save the same type of the right bracket
            }else if(c == '['){
                stack.push(']');
            }else if(c == '{'){
                stack.push('}');
            }else if(stack.isEmpty()||stack.pop()!=c){ //if the stack is empty or popping the last-in character is not the right one,return false  
                return false;
            }
        }
        return stack.isEmpty();
    }
}





评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值