Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
18 changes: 18 additions & 0 deletions src/main/java/com/thealgorithms/strings/ValidParentheses.java
Original file line number Diff line number Diff line change
Expand Up @@ -38,4 +38,22 @@ public static boolean isValid(String s) {
}
return head == 0;
}
public static boolean isValidParentheses(String s) {
int i = -1;
char[] stack = new char[s.length()];
String openBrackets = "({[";
String closeBrackets = ")}]";
for (char ch : s.toCharArray()) {
if (openBrackets.indexOf(ch) != -1) {
stack[++i] = ch;
} else {
if (i >= 0 && openBrackets.indexOf(stack[i]) == closeBrackets.indexOf(ch)) {
i--;
} else {
return false;
}
}
}
return i == -1;
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -10,15 +10,18 @@ public class ValidParenthesesTest {
@Test
void testOne() {
assertTrue(ValidParentheses.isValid("()"));
assertTrue(ValidParentheses.isValidParentheses("()"));
}

@Test
void testTwo() {
assertTrue(ValidParentheses.isValid("()[]{}"));
assertTrue(ValidParentheses.isValidParentheses("()[]{}"));
}

@Test
void testThree() {
assertFalse(ValidParentheses.isValid("(]"));
assertFalse(ValidParentheses.isValidParentheses("(]"));
}
}