1. <?php
    2. class Solution {
    3. /**
    4. * '(()' -> 2
    5. * ')()())' -> 4
    6. * @param $s
    7. * @return int|mixed
    8. */
    9. public function longestValidParentheses($s) {
    10. $max = 0;
    11. $start = 0;
    12. $stack = new SplStack();
    13. for ($i = 0; $i < strlen($s); $i++) {
    14. if ($s[$i] == '(') {
    15. $stack->push($i);
    16. } else {
    17. if ($stack->isEmpty()) {
    18. $start = $i + 1;
    19. } else {
    20. $stack->pop();
    21. $max = $stack->isEmpty() ? max($max, $i - $start + 1) : max($max, $i - $stack->top());
    22. }
    23. }
    24. }
    25. return $max;
    26. }
    27. }
    28. $s = ')(((()())(';
    29. $cls = new Solution();
    30. $r = $cls->longestValidParentheses($s);
    31. echo $r;