博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
LeetCode刷题:20. Valid Parentheses
阅读量:4040 次
发布时间:2019-05-24

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

LeetCode刷题:20. Valid Parentheses

原题链接:

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


算法设计

package com.bean.algorithm.basic;import java.util.Stack;public class ValidParentheses {	public boolean isValid(String s) {		if (s == "" || s.isEmpty())			return true;		Stack stack = new Stack();		for (int index = 0; index < s.length(); index++) {			char ch = s.charAt(index);			if (ch == '(' || ch == '[' || ch == '{') {				stack.push(ch);			} else {				char expected;				if (ch == ')')					expected = '(';				else if (ch == ']')					expected = '[';				else					expected = '{';				if (stack.isEmpty()) {					return false;				}				char actual = (char) stack.pop();				if (actual != expected) {					return false;				}			}		}		return stack.isEmpty();	}		public static void main(String[] args) {				ValidParentheses vp=new ValidParentheses();				//String input="()[]{}";		String input="([)]";				boolean flag=vp.isValid(input);		System.out.println("flag is: "+flag);	}}

程序运行结果:

当 input = “()[]{}”时,返回 flag = true;

当 input = “([)]”时,返回 flag = false

 

转载地址:http://sntdi.baihongyu.com/

你可能感兴趣的文章
oracle exp 导出表时会发现少表,空表导不出解决方案
查看>>
ORA-14450:试图访问已经在使用的事务处理临时表
查看>>
ORACLE RMAN 各种场景恢复
查看>>
oracle 自动导出package/package body/procedure 等为sql文件并且自动上传到ftp服务器上
查看>>
linux 下 su - oracle 切换不了
查看>>
初学MonggoDb—Linux平台安装MongoDB
查看>>
使用“rz -be”命令上传文件至服务器;使用“sz 文件名”从服务器下载文件到本地
查看>>
mysql:pt-online-schema-change 在线修改表
查看>>
oracle 调整表空间大小 (resize)
查看>>
Oracle scn健康状态检查脚本—scnhealthcheck.sql
查看>>
Redis+TwemProxy(nutcracker)集群部署测试
查看>>
Docker mysql8.0 oltp 性能测试
查看>>
oracle 只开启一个监听端口,却多个端口都可以连接
查看>>
ORA-00600: internal error code, arguments: [qcisSetPlsqlCtx:tzi init], [], [],
查看>>
CAP理论被应用在何方?
查看>>
RocketMQ集群安装部署
查看>>
kafka搭建入门
查看>>
高并发秒杀系统的设计思考!
查看>>
K8S概念与架构总结
查看>>
架构设计和代码开发中的一些常用原则
查看>>