package com.imooc.test;
import java.util.Scanner;
import java.util.Stack;
/**
* @author tangxuejun
* @version 2018/9/29 5:42 PM
* leeteCode:20括号匹配
*/
public class BracketTest {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
String pattern = scanner.next();
System.out.println(isValid(pattern));
}
private static boolean isValid(String s) {
if (s == null) {
return false;
}
Stack<String> stack = new Stack<>();
String[] splitStr = s.split("");
//是否是成对
if (splitStr.length % 2 != 0) {
return false;
}
for (String s1 : splitStr) {
switch (s1) {
//将各种左括号入栈
case "(":
case "{":
case "[":
stack.push(s1);
break;
//如果遇到一个右括号,则去栈顶匹配其对应的左括号,如果不相等,则返回false,否则继续执行,知道全部执行成功
case ")":
if (stack.empty() || !stack.pop().equals("(")) {
return false;
}
break;
case "}":
if (stack.empty() || !stack.pop().equals("{")) {
return false;
}
break;
case "]":
if (stack.empty() || !stack.pop().equals("[")) {
return false;
}
break;
}
}
return true;
}
}
LeetCode:20
最新推荐文章于 2022-11-11 15:22:35 发布