TypechoJoeTheme

IT技术分享

统计

[LeetCode 20] Valid Parentheses [Java]

2017-11-23
/
0 评论
/
766 阅读
/
正在检测是否收录...
11/23

1. Description

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.

2. Code

import java.util.Stack;

public class LeetCode0020 {
    public boolean isValid(String s)
    {
        if (s == null || s.length() == 0) {
            return false;
        }

        Stack stack = new Stack();

        for (int i = 0; i < s.length(); i++) {
            char c = s.charAt(i);

            if (!stack.isEmpty()) {
                int top = stack.peek();
                if (top == '(' && c == ')' || top == '[' && c == ']' || top == '{' && c == '}') {
                    stack.pop();
                }
                else {
                    stack.push(c);
                }
            }
            else if (c == ')' || c == ']' || c == '}') {
                return false;
            }
            else {
                stack.push(c);
            }
        }
        return stack.isEmpty();
    }

    public static void main(String[] args)
    {
        LeetCode0020 leetcode = new LeetCode0020();
        System.out.println(leetcode.isValid("()[]"));
    }
}
Stack
朗读
赞 · 0
版权属于:

IT技术分享

本文链接:

https://idunso.com/archives/1272/(转载时请注明本文出处及文章链接)