博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
[leetcode] Valid Parentheses
阅读量:7142 次
发布时间:2019-06-29

本文共 1144 字,大约阅读时间需要 3 分钟。

hot3.png

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:经典的栈匹配。一个栈,左符号入栈,右符号出栈。最后检查栈是否为空。

public class Solution {	public boolean isValid(String s) {		if (s == null || s.length() == 0)			return true;		Stack
stack = new Stack
(); int n = s.length(); for (int i = 0; i < n; i++) { char ch = s.charAt(i); if (ch == '(' || ch == '{' || ch == '[') stack.push(ch); else { if (stack.isEmpty()) return false; char out = stack.pop(); if (ch == ')' && out != '(' || ch == '}' && out != '{' || ch == ']' && out != '[') return false; } } if (!stack.isEmpty()) return false; return true; } public static void main(String[] args) { // true System.out.println(new Solution().isValid("()")); // true System.out.println(new Solution().isValid("()[]{}")); // false System.out.println(new Solution().isValid("(]")); // false System.out.println(new Solution().isValid("([)]")); }}

转载于:https://my.oschina.net/jdflyfly/blog/283682

你可能感兴趣的文章
ChaosConf 2018:混沌实验的演变
查看>>
区块链技术精华:四十种智能合约支持平台(三)
查看>>
MySQL · B+树并发控制机制的前世今生
查看>>
ArchSummit全球架构师峰会 重新定位架构师的价值
查看>>
微软在C# 8中引入预览版可空引用类型
查看>>
FoundationDB宣布记录层支持关系数据库语义、模式管理和索引功能
查看>>
一个月6次泄露,为啥大家用Elasticsearch总不设密码?
查看>>
去哪儿网消息队列设计与实现
查看>>
Racket 6.7最新版本:提供对Android App的支持及改进的REPL等等
查看>>
微软宣布公开预览其内容分发网络
查看>>
IBM、Google、Oracle三巨头的公有云之殇(下)
查看>>
Rust编程语言的核心部件
查看>>
简明高效的 Java 并发编程学习指南
查看>>
Git 2.20的重大更新:侧重可用性和性能
查看>>
区块链和数据科学:如果同时应用这两种技术,将会实现什么?
查看>>
51信用卡Android 架构演进实践
查看>>
.NET Core如何为项目提供高性能解决方案?
查看>>
逃离方法牢笼
查看>>
Stack Overflow技术报告给开发者哪些启示
查看>>
如何做自动化测试?
查看>>