codility之Brackets

Brackets

题目链接:

Brackets

题目解析

其实就是平衡符号。

如何解决?

利用栈就可以搞定, 具体不明白的看书吧。

talk is cheap, show me the code~

代码:



function solution($S) {
    // write your code in PHP5.5
    $open_symb  = array( '{', '[', '(' );
    $close_symb = array( '}', ']', ')' );
    $check = array();
    for($i = 0; $i< strlen($S); $i++) {
        $v = $S[$i];
        if (in_array($v, array_values($open_symb))) {
            array_push($check, $v);
        } elseif (in_array($v, array_values($close_symb))) {
            $symbol = array_pop($check);
            $cor_symbol = array_search($v, $close_symb);
            if ($symbol !== $open_symb[$cor_symbol]) {
                return  0;
            }
        }
    }
    
    if (!empty($check)) {
        return 0;
    }
  

Leave a Reply

Your email address will not be published. Required fields are marked *


To create code blocks or other preformatted text, indent by four spaces:

    This will be displayed in a monospaced font. The first four 
    spaces will be stripped off, but all other whitespace
    will be preserved.
    
    Markdown is turned off in code blocks:
     [This is not a link](http://example.com)

To create not a block, but an inline code span, use backticks:

Here is some inline `code`.

For more help see http://daringfireball.net/projects/markdown/syntax