【Java】括号匹配
{}
括号匹配模式
解题思路
栈
import java.util.Scanner;
import java.util.Stack;
/** * @Author bennyrhys * @Date 2020-09-20 15:24 */
public class T71 {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
String s = sc.nextLine();
System.out.println(isS(s));
}
private static boolean isS(String s) {
Stack<Character> stack = new Stack<>();
for (int i = 0; i < s.length(); i++) {
char c = s.charAt(i);
if (c == '(')
stack.push(')');
if (c == '[')
stack.push(']');
if (c == '{')
stack.push('}');
if (c == ')' || c == ']' || c== '}') {
if (stack.size() == 0)
return false;
if (stack.pop() != c)
return false;
}
}
if (stack.size() != 0)
return false;
return true;
}
}
还没有评论,来说两句吧...