Created
November 20, 2019 06:50
-
-
Save marisnb/5020935c2fdde97ecea0f97903cce78b to your computer and use it in GitHub Desktop.
Valid Parentheses
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// Given a string containing just the characters '(', ')', '{', '}', '[' and ']', determine if the input string is valid. | |
// An input string is valid if: | |
// Open brackets must be closed by the same type of brackets. | |
// Open brackets must be closed in the correct order. | |
// Note that an empty string is also considered valid. | |
// Example 1: | |
// Input: "()" | |
// Output: true | |
// Example 2: | |
// Input: "()[]{}" | |
// Output: true | |
// Example 3: | |
// Input: "(]" | |
// Output: false | |
// Example 4: | |
// Input: "([)]" | |
// Output: false | |
// Example 5: | |
// Input: "{[]}" | |
// Output: true | |
class Parentheses { | |
public static void main(String args[]) { | |
if(isValid("()")) { | |
System.out.println("Valid"); | |
} else { | |
System.out.println("Not Valid"); | |
} | |
} | |
public static boolean isValid(String s) { | |
Stack<Character> stack = new Stack<Character>(); | |
for(int i = 0; i < s.length(); i++) { | |
char c = s.charAt(i); | |
if (c == '{' || c == '(' || c == '[') { | |
stack.push(c); | |
} | |
if (c == '}' || c == ')' || c == ']') { | |
if(stack.empty()) { | |
return false; | |
} | |
else if (!isMatchingPair(stack.pop(), c) ) | |
{ | |
return false; | |
} | |
} | |
} | |
return stack.empty(); | |
} | |
private static boolean isMatchingPair(char character1, char character2) | |
{ | |
return (character1 == '(' && character2 == ')') || (character1 == '{' && character2 == '}') || | |
(character1 == '[' && character2 == ']'); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment