首页 > 其他 > 详细

Lc20-Valid Parentheses

时间:2020-01-14 12:36:07      阅读:104      评论:0      收藏:0      [点我收藏+]
import java.util.Stack;

/*
 * 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

来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/valid-parentheses
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。
 */
public class Lc20 {
    public static boolean isValid(String s) {
        Stack<Character> stack = new Stack<Character>();
        boolean isValid = false;

        char[] ch = s.toCharArray();
        for (char c : ch) {
            if (( == c) {
                stack.push(c);
            } else if ([ == c) {
                stack.push(c);
            } else if ({ == c) {
                stack.push(c);
            } else if (!stack.isEmpty()) {
                if () == c) {
                    Character temp = stack.pop();
                    if (( != temp) {
                        return false;
                    }
                } else if (] == c) {
                    Character temp = stack.pop();
                    if ([ != temp) {
                        return false;
                    }
                } else if (} == c) {
                    Character temp = stack.pop();
                    if ({ != temp) {
                        return false;
                    }
                }
            } else {
                return false;
            }

        }
        if (stack.isEmpty()) {
            isValid = true;
        }
        return isValid;
    }

    public static void main(String[] args) {
        String s = "{";
        System.out.println(isValid(s));
    }

}

Lc20-Valid Parentheses

原文:https://www.cnblogs.com/xiaoshahai/p/12191059.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!