Brackets::solution()   C
last analyzed

Complexity

Conditions 12
Paths 11

Size

Total Lines 29
Code Lines 20

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
c 0
b 0
f 0
dl 0
loc 29
rs 5.1612
cc 12
eloc 20
nc 11
nop 1

How to fix   Complexity   

Long Method

Small methods make your code easier to understand, in particular if combined with a good name. Besides, if your method is small, finding a good name is usually much easier.

For example, if you find yourself adding comments to a method's body, this is usually a good sign to extract the commented part to a new method, and use the comment as a starting point when coming up with a good name for this new method.

Commonly applied refactorings include:

1
<?php
2
3
namespace Lesson05;
4
5
class Brackets
6
{
7
    public function solution($S)
8
    {
9
        $length = strlen($S);
10
        $map = [')' => '(', '}' => '{', ']' => '['];
11
        if ($length) {
12
            $parentheses = [];
13
            for ($i = 0; $i < $length; $i++) {
14
                $c = $S[$i];
15
                if ($c == '(' || $c == '{' || $c == '[') {
16
                    array_push($parentheses, $c);
17
                } elseif ($c == ')' || $c == '}' || $c == ']') {
18
                    if (empty($parentheses)) {
19
                        return 0;
20
                    }
21
                    $v = array_pop($parentheses);
22
                    if ($map[$c] != $v) {
23
                        return 0;
24
                    }
25
                }
26
            }
27
            if (empty($parentheses)) {
28
                return 1;
29
            } else {
30
                return 0;
31
            }
32
        }
33
34
        return 1;
35
    }
36
}
37