vlambda博客
学习文章列表

数据结构与算法-有效括号序列

题目描述:

给出一个仅包含字符'(',')','{','}','['和']',的字符串,判断给出的字符串是否是合法的括号序列
括号必须以正确的顺序关闭,"()"和"()[]{}"都是合法的括号序列,但"(]""([)]"不合法

示例1

输入


"["

返回值


false

示例2

输入


"[]"

返回值


true


解题思路:

 用栈这种数据结构


代码实现:

import java.util.Stack;
public class IsValidString { private static final char SML_LEFT = '('; private static final char SML_RIGHT = ')'; private static final char MID_LEFT = '['; private static final char MID_RIGHT = ']'; private static final char BIG_LEFT = '{'; private static final char BIG_RIGHT = '}'; /** * * @param s string字符串 * @return bool布尔型 */ public static boolean isValid (String s) { // write code here if (null == s){ return false; } int length = s.length(); if (length%2==1){ return false; } Stack<Character> stk = new Stack<>(); for (int i=0; i<length; i++){ if (stk.isEmpty()){ //如果栈中为空 if (s.charAt(i)==SML_RIGHT || s.charAt(i)==MID_RIGHT || s.charAt(i)==BIG_RIGHT){ //在栈中为空的情况下,当前的字符为},],),则不符合,返回false return false; }else if (s.charAt(i)==SML_LEFT || s.charAt(i)==MID_LEFT || s.charAt(i)==BIG_LEFT){ //在栈中为空的情况下,当前的字符为{,[,(,则做入栈处理 stk.push(s.charAt(i)); }else{ return false; } }else{//如果栈中不为空 if (s.charAt(i)==SML_RIGHT || s.charAt(i)==MID_RIGHT || s.charAt(i)==BIG_RIGHT){ //在栈中不为空的情况下,当前的字符为},],),判断栈顶元素与当前字符是否匹对 char stkTop = stk.peek(); if (s.charAt(i)==SML_RIGHT && stkTop == SML_LEFT){ stk.pop(); }else if (s.charAt(i)==MID_RIGHT && stkTop == MID_LEFT){ stk.pop(); }else if (s.charAt(i)==BIG_RIGHT && stkTop == BIG_LEFT){ stk.pop(); }else{ return false; } }else if (s.charAt(i)==SML_LEFT || s.charAt(i)==MID_LEFT || s.charAt(i)==BIG_LEFT){ stk.push(s.charAt(i)); }else{ return false; } } } return stk.isEmpty(); }
public static void main(String[] args){ String s = "[{{]}}()"; boolean res = isValid(s); System.out.println(res); }}