LeetCode 腾讯精选50题--有效的括号

根据题意,第一反应就是使用栈,左右括号相匹配,则将左括号出栈,否则将左括号入栈。

这里我用数组配合“指针”模拟栈的入栈与出栈操作,初始时指针位置指向0,表示空栈,凡遇上左括号则直接入栈,若遇上有括号,对比数组尾部的括号与右括号是否匹配,若不匹配直接返回false;否则将指针数值减1,若对比结束后,指针数值为0,则返回true,否则为false

class Solution {
    public boolean isValid(String s) {
        if(s.length() ==0){
            return true;
        }

        int left = 0;

        char[] schars = s.toCharArray();
        char[] temp = new char[s.length()];

        for (int i = 0; i <s.length() ; i++) {
            if(schars[i] == '(' || schars[i] == '{' || schars[i] == '['){
                temp[left++] = schars[i];
            }else {
                if(left < 1){
                    return false;
                }
                if(temp[left-1] == '('){

                    if(schars[i] == ')'){
                        left--;
                    }else {
                        return false;
                    }
                }else if(temp[left-1] == '{'){

                    if(schars[i] == '}'){
                        left--;
                    }else {
                        return false;
                    }

                }else if(temp[left-1] == '['){

                    if(schars[i] == ']'){
                        left--;
                    }else {
                        return false;
                    }

                }

            }

        }

        return left == 0;
    }
}

猜你喜欢

转载自www.cnblogs.com/Kaithy-Rookie/p/11297986.html