美文网首页Leetcode题解-PHP版
Leetcode PHP题解--D135 20. Valid P

Leetcode PHP题解--D135 20. Valid P

作者: skys215 | 来源:发表于2021-10-12 21:40 被阅读0次

    D135 20. Valid Parentheses

    题目链接

    20. Valid Parentheses

    题目分析

    这道题也比较经典,就是括号匹配题。

    给出一个包含小、中、大括号的字符串,判断左右括号是否匹配。

    要注意出现顺序,不能串。也要注意有可能会出现空字符串。

    解题思路

    这道题的经典做法是用栈来实现。

    遇到左括号时,直接入栈。遇到右括号时,判断当前括号类型和栈顶端,即出栈时的括号类型是否相同。如果相同则继续判断。如果不同则返回false。

    遍历完所有字符时,如果栈内还有括号剩余,即有括号没有被匹配,也视为false。

    最终代码

    <?php
    
    class Solution {
    
        /**
         * @param String $s
         * @return Boolean
         */
        function isValid($s) {
            if(!strlen($s)){
                return true;
            }
            $parentheses_array = str_split($s);
            $stack = [];
            foreach($parentheses_array as $parenthes){
                if($parenthes == '(' 
                  || $parenthes == '['
                  || $parenthes == '{'){
                    $stack[] = $parenthes;
                }
                else{
                    $prev = array_pop($stack);
                    if(( $prev== '(' && $parenthes == ')')
                       || ($prev == '[' && $parenthes == ']')
                       || ($prev == '{' && $parenthes == '}')
                       ){
                        continue;
                    }
                    return false;
                }
            }
            var_dump(count($stack));
            if(count($stack)){
                return false;
            }
            else{
                return true;
            }
        }
    }
    

    若觉得本文章对你有用,欢迎用爱发电资助。

    相关文章

      网友评论

        本文标题:Leetcode PHP题解--D135 20. Valid P

        本文链接:https://www.haomeiwen.com/subject/bhmjoltx.html