栈
import java.util.Scanner;
import java.util.Deque;
public class Algorithm {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.println(new Algorithm().isValid(scanner.nextLine()));
}
public boolean isValid(String s) {
/**
* Java推荐使用Deque类来实现栈(虽然也会破坏封装)
*/
Deque<Character> stack = new ArrayDeque<>();
for (int i = 0; i < s.length(); i++) {
char c = s.charAt(i);
/**
* 只将左括号入栈,右括号用来和栈顶元素进行比较
*/
if (c == '(' || c == '[' || c == '{') {
stack.push(c);
}
else {
if (stack.isEmpty()) {
return false;
}
char top = stack.pop();
if (c == ')' && top != '(') {
return false;
}
if (c == ']' && top != '[') {
return false;
}
if (c == '}' && top != '{') {
return false;
}
}
}
/**
* 如果括号全部匹配,栈应该为空
*/
return stack.isEmpty();
}
}
/**
* 时间复杂度 O(n)
* 空间复杂度 O(n)
*/
https://leetcode-cn.com/problems/valid-parentheses/