Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Added solution for Valid Parenthesis problem #313

Merged
merged 1 commit into from
Oct 4, 2024

Conversation

Sidhesh-Goud
Copy link
Contributor

The isValid function checks if the input string s, which consists of parentheses, brackets, and braces, is valid. A string is considered valid if every opening bracket has a corresponding closing bracket in the correct order.
Parameters:
s (string): A string consisting of the characters (, ), {, }, [ and ].
Returns:
boolean: Returns true if the string is valid otherwise, returns false.

Logic:
Initialization:

  • A mapping object elts is created to hold pairs of opening and closing brackets.
  • An empty array stack is initialized to keep track of the opening brackets encountered in the string.

Iteration through the string:

  • The function iterates through each character in the string s.
  • If the character is an opening bracket (i.e., it exists in the elts object), it is pushed onto the stack.
  • If the character is a closing bracket:
  • The function first checks if the stack is empty. If it is, it means there's no matching opening bracket, and the function returns false.
  • If the stack is not empty, the function pops the top element from the stack (the last opening bracket) and checks if it matches the current closing bracket. If it does not match, the function returns false.

Final Validation:

  • After iterating through all characters, the function checks if the stack is empty. If it is empty, all opening brackets had matching closing brackets, and the function returns true. If not, it returns false.

Example:

  • console.log(isValid("()")); // true
  • console.log(isValid("()[]{}")); // true
  • console.log(isValid("(]")); // false
  • console.log(isValid("([)]")); // false
  • console.log(isValid("{[]}")); // true

@Saloni6111 Saloni6111 added the hacktoberfest-accepted contribute for hacktoberfest 2024 label Oct 4, 2024
@Saloni6111 Saloni6111 merged commit 01a2225 into Saloni6111:main Oct 4, 2024
1 check passed
@Sidhesh-Goud Sidhesh-Goud deleted the Valid-Parenthesis branch October 5, 2024 03:47
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
hacktoberfest-accepted contribute for hacktoberfest 2024
Projects
None yet
Development

Successfully merging this pull request may close these issues.

2 participants