OneCoder Avatar
OneCodercoderli.com · 955 篇博文
{ } Java

Java 服务端架构

Spring、Netty、日志框架与工程化实战

🎨 视觉封面

LeetCode Valid Parentheses

📅 2017-10-18·✍️ onecoder·计算中...·⏱️ 6 分钟
#LeetCode#Java

Problem

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.

即判断一个只包含括号的字符串,是不是合法的。

Java 实现

JAVA

package com.coderli.leetcode.algorithms.easy;

/**
 * Given a string containing just the characters '(', ')', '{', '}', '[' and ']', determine if the input string is valid.
 * <p>
 * The brackets must close in the correct order, "()" and "()[]{}" are all valid but "(]" and "([)]" are not.
 *
 * @author li.hzh 2017-10-18
 */
public class ValidParentheses {

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

    public boolean isValid(String s) {
        if (s.length() % 2 != 0) {
            return false;
        }
        if (s.length() == 0) {
            return true;
        }
        char[] stack = new char[s.length()];
        int lastIndex = 0;
        for (int i = 0; i < s.length(); i++) {
            char currentChar = s.charAt(i);
            if (currentChar == '(' || currentChar == '[' || currentChar == '{') {
                stack[lastIndex] = currentChar;
                lastIndex++;
                continue;
            } else {
                if (lastIndex == 0) {
                    return false;
                }
                char lastValue = stack[lastIndex - 1];
                lastIndex--;
                if (currentChar == ')') {
                    if (lastValue != '(') {
                        return false;
                    }
                } else if (currentChar == ']') {
                    if (lastValue != '[') {
                        return false;
                    }
                } else {
                    if (lastValue != '{') {
                        return false;
                    }
                }
            }
        }
        if (lastIndex != 0) {
            return false;
        }
        return true;
    }
}

分析

因为要配对的,首先先pass掉长度是奇数的输入。剩下的输入,如果是左括号,则放入栈中。如果是右括号,从栈里取出最后一个元素进行配对。如果配对则继续。不配对,则说明字符串不合法。

💡 OneCoder 资源指引

所有代码开源上传至 GitHub:yummy-code 仓库 · GESP 专题站:GESP WIKI

🤝 技术交流与答疑

欢迎加入:C++ GESP/CSP 考级答疑群(688906745)Java/Python交流群(982860385),点击可直接加群。

📚

猜你想读 · 相关文章推荐

OneCoder

OneCoder (lihongzheshuai)

一个中年人的自留地,记录学习 C++、GESP/NOI、Java、Python 与算法架构的心得体会。本站唯一网址:coderli.com

💬 读者留言与交流

0 条讨论
✨ 支持 Markdown 语法格式
还没有留言,快来成为第一个讨论者吧!