package day04.first;
import java.util.Stack;
public class Solution {
public static void main(String[] args) {
String str = "(124546{[})";
boolean a = isValid(str);
System.out.println(a);
}
public static boolean isValid (String s){
//定义左括号和右边的括号
char [] parentheses = { '(' , '[' , '{' , ')' , ']' , '}'} ;
int i= 0 ;
char c ;
int [] sum = {0,0,0};
Stack<Integer> stack = new Stack<>();
while (i < s.length()){
c = s.charAt(i) ;
for (int j = 0; j <= 2 ; j++) {
if(c == parentheses[j]){
stack.push(j);
sum[j] ++ ;
}else if (c == parentheses[j + 3 ]){
if(stack.size() ==0 || stack.peek() != j ){
return false ;
}
stack.pop();
sum[j] -- ;
}else {
}
}
i++ ;
}
for (int j = 0; j <= 2 ; j++) {
if (sum[j] != 0) {
return false;
}
}
return true ;
}
}
class Solution {
public boolean isValid(String s) {
int n = s.length();
if (n % 2 == 1) {
return false;
}
Map<Character, Character> pairs = new HashMap<Character, Character>() {{
put(')', '(');
put(']', '[');
put('}', '{');
}};
Deque<Character> stack = new LinkedList<Character>();
for (int i = 0; i < n; i++) {
char ch = s.charAt(i);
if (pairs.containsKey(ch)) {
if (stack.isEmpty() || stack.peek() != pairs.get(ch)) {
return false;
}
stack.pop();
} else {
stack.push(ch);
}
}
return stack.isEmpty();
}
}