LeetCode Tencent's selection of 50 questions - Effective brackets

According to the meaning of problems, the first reaction is to use the stack, left and right parentheses match, then left parenthesis from the stack, the stack would otherwise be left parenthesis.

Here I use an array with "pointer" simulated stack push and pop operation, the initial position of the pointer points to 0, indicates empty stack, where the stack directly encounter the left bracket, parentheses encountered if the brackets, the end of the array comparison the right bracket matches, if not directly match return false; otherwise, the pointer value is decremented by 1, if after the comparison, the pointer value is 0, returns true, false otherwise

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

 

Guess you like

Origin www.cnblogs.com/Kaithy-Rookie/p/11297986.html