题目描述
给出一个仅包含字符’(’,’)’,’{’,’}’,’[‘和’]’,的字符串,判断给出的字符串是否是合法的括号序列
括号必须以正确的顺序关闭,"()“和”()[]{}“都是合法的括号序列,但”(]“和”([)]"不合法。
解题思路
运用栈的后进先出的原理
package com.example.demotest.leetcode;
import java.util.Stack;
/**
* 题目描述
* 给出一个仅包含字符'(',')','{','}','['和']',的字符串,判断给出的字符串是否是合法的括号序列
* 括号必须以正确的顺序关闭,"()"和"()[]{}"都是合法的括号序列,但"(]"和"([)]"不合法。
*/
public class IsValidSolution {
/**
*
* @param s string字符串
* @return bool布尔型
*/
public static boolean isValid (String s) {
Stack<Character> stack = new Stack<>();//后进先出,后进的元素在栈顶
for(char c : s.toCharArray()){
if(c == '('){
stack.push(')');
}else if(c == '{'){
stack.push('}');
}else if(c == '['){
stack.push(']');
}else if(stack.isEmpty() || stack.pop() != c){
return false;
}
}
return stack.isEmpty();
}
public static void main(String[] args) {
String s = "{()}";
System.out.println(isValid(s));;
}
}