0
点赞
收藏
分享

微信扫一扫

CSDN每日一练_1(20220212)有效的括号

心如止水_c736 2022-02-12 阅读 39
算法

 

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();
    }
}

 

举报

相关推荐

0 条评论