leetcode刷题-堆栈3

来源:互联网 发布:淘宝第五大道是正品吗 编辑:程序博客网 时间:2024/06/05 09:08
package com.zwd.wkst.leetcode.stack;import java.util.Stack;/** * Created by zhangwd4 on 2017/11/2. * * 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. 思路: 当符号是 左边的符号 时,压入堆栈; 当符号是右边符号时:1 堆栈不为空,2 栈顶元素是相对应的左边符号;而且如果不全满足,直接返回false; 当程序运行完,栈是空,返回true */public class Solution2 {    public boolean isValid(String s) {        if(s ==null || s.isEmpty()){            return false;        }        Stack<Character> stack = new Stack<>();        for(char c : s.toCharArray()){            if(c == '(' || c== '[' || c == '{')                stack.push(c);            else if(c == ')' && !stack.empty() && stack.peek() == '(')                stack.pop();            else if(c == ']' && !stack.empty() && stack.peek() == '[')                stack.pop();            else if(c == '}' && !stack.empty() && stack.peek() == '{')                stack.pop();            else                return false;        }        return stack.isEmpty();    }}

原创粉丝点击