PHP, MySQL, JavaScript Solutions Since 2000

Nesting Demo Task at Codility.com

Lesson 5 – Stacks and Queues – Nesting demo task solution code written in php. Gives 100/100 score at the time of publishing. The description of the problem is copyrighted, so please see the following link for it: https://codility.com/demo/take-sample-test/nesting

Solution in php:

PHP

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

25

functionsolution($S){

$s=preg_replace('~[^\(\)]~','',$S);

if($S<>$s){

return0;

}

$S=str_split($S);

if(empty($S)){

return1;

}

$counter=0;

foreach($Sas$v){

switch($v){

case'(':

$counter++;

break;

case')':

$counter--;

break;

}

if($counter<0){

return0;

}

}

return$counter==0?1:0;

}

Given “AS IS”, can be ported from other languages from solutions found on the internet, please use with care.