Possible solution

Here’s one way to solve the problem:

function isValid($s) {
  $stack = [];
  $map = [
    ')' => '(',
    '}' => '{',
    ']' => '['
  ];

  for ($i = 0; $i < strlen($s); $i++) {
    $char = $s[$i];

    if (in_array($char, ['(', '{', '['])) {
      // If the character is an opening bracket, push it onto the stack
      array_push($stack, $char);
    } else {
      // If the character is a closing bracket, pop the top element from the stack
      // and compare it to the corresponding opening bracket using the map
      if (count($stack) == 0) {
        // If the stack is empty, the string is not valid
        return false;
      }

      $top = array_pop($stack);
      if ($top != $map[$char]) {
        // If the opening bracket does not match the closing bracket, the string is not valid
        return false;
      }
    }
  }

  // If the stack is not empty at the end of the loop, the string is not valid
  return count($stack) == 0;
}

The function uses a stack to keep track of the opening brackets in the string. It also uses a map to map the closing brackets to their corresponding opening brackets.

The function loops through each character in the string. If the character is an opening bracket, it is pushed onto the stack. If the character is a closing bracket, the top element is popped from the stack and compared to the corresponding opening bracket using the map. If the opening bracket does not match the closing bracket, the string is not valid and the function returns false.

At the end of the loop, if the stack is not empty, the string is not valid and the function returns false. Otherwise, the string is valid and the function returns true.

LEAVE A REPLY

Please enter your comment!
Please enter your name here