Advertisement
exmkg

Untitled

Sep 28th, 2024
83
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 1.43 KB | None | 0 0
  1. class Solution {
  2.     public boolean isValid(String s) {
  3.         // Create an empty stack to keep track of opening brackets
  4.         Stack<Character> stack = new Stack<Character>();
  5.  
  6.         // Loop through every character in the string
  7.         for (int i = 0; i < s.length(); i++) {
  8.             char c = s.charAt(i);
  9.             // If the character is an opening bracket, push it onto the stack
  10.             if (c == '(' || c == '[' || c == '{') {
  11.                 stack.push(c);
  12.             } else { // If the character is a closing bracket
  13.                 // If the stack is empty, there is no matching opening bracket, so return false
  14.                 if (stack.isEmpty()) {
  15.                     return false;
  16.                 }
  17.                 // Otherwise, get the top of the stack and check if it's the matching opening bracket
  18.                 char top = stack.peek();
  19.                 if ((c == ')' && top == '(') || (c == ']' && top == '[') || (c == '}' && top == '{')) {
  20.                     // If it is, pop the opening bracket from the stack
  21.                     stack.pop();
  22.                 } else { // Otherwise, the brackets don't match, so return false
  23.                     return false;
  24.                 }
  25.             }
  26.         }
  27.         // If the stack is empty, all opening brackets have been closed, so return true
  28.         // Otherwise, there are unmatched opening brackets, so return false
  29.         return stack.isEmpty();
  30.     }
  31. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement