Skip to content

Commit

Permalink
20. Valid Parentheses
Browse files Browse the repository at this point in the history
  • Loading branch information
xtenzQ committed Jul 29, 2024
1 parent a0037f2 commit 7472d4b
Show file tree
Hide file tree
Showing 2 changed files with 63 additions and 0 deletions.
Original file line number Diff line number Diff line change
@@ -0,0 +1,39 @@
package com.xtenzq.stack;

import java.util.Map;
import java.util.Stack;

public class Stacks {

/**
* Determines if the input string is valid.
* <p>
* An input string is valid if:
* <ol>
* <li>Open brackets must be closed by the same type of brackets;</li>
* <li>Open brackets must be closed in the correct order;</li>
* <li>Every close bracket has a corresponding open bracket of the same type.</li>
* </ol>
*
* @param s string to validate
* @return {@code true} if string is valid, {@code false} otherwise
* @implNote This method runs in {@code O(n)} time complexity, where {@code n} is the length of {@code s}.
* @see <a href="https://leetcode.com/problems/valid-parentheses/">20. Valid Parentheses</a>
*/
public static boolean isValid(String s) {
Map<Character, Character> brackets = Map.of('(', ')', '{', '}', '[', ']');

Stack<Character> stack = new Stack<>();
for (int i = 0; i < s.length(); i++) {
char c = s.charAt(i);
if (brackets.containsKey(c)) {
stack.push(c);
} else {
if (stack.empty() || brackets.get(stack.pop()) != c) {
return false;
}
}
}
return stack.empty();
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,24 @@
package com.xtenzq.stack;

import org.junit.jupiter.api.Test;

import static com.xtenzq.stack.Stacks.isValid;
import static org.junit.jupiter.api.Assertions.*;

class StacksTest {

@Test
void isValid_case1() {
assertTrue(isValid("()"));
}

@Test
void isValid_case2() {
assertTrue(isValid("()[]{}"));
}

@Test
void isValid_case3() {
assertFalse(isValid("(]"));
}
}

0 comments on commit 7472d4b

Please sign in to comment.