[LeetCode]20. Valid Parentheses

来源:互联网 发布:log4j2 json 配置 编辑:程序博客网 时间:2024/06/11 01:04

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.

解:栈的基本使用。

public class Solution {    public boolean isValid(String s) {         Stack<String> stack = new Stack<>();        char cur,top;        for (int i = 0;i < s.length();i++){            cur = s.charAt(i);            if (cur == '(' || cur == '[' || cur == '{'){                stack.push(String.valueOf(cur));            }else {                if (stack.empty()) return false;                top = stack.pop().charAt(0);                if (cur == ')' && top != '(')  return false;                if (cur == ']' && top != '[')  return false;                if (cur == '}' && top != '{')  return false;            }        }        if (!stack.empty()) return false;        return true;    }}
0 0
原创粉丝点击