Created
July 8, 2021 02:58
-
-
Save YusufAbdelaziz/e237e40c53ea61b5afac92d6e425048b to your computer and use it in GitHub Desktop.
Solving brackets sequence problem
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
package datastructures.main; | |
import java.util.Stack; | |
public class Brackets { | |
public static void main(String[] args) { | |
boolean isValid = false; | |
String inputString = "[()]()()()"; | |
Stack<Character> myStack = new Stack<>(); | |
boolean valid = true; | |
for (int i = 0; i < inputString.length(); i++) { | |
if (!valid) break; | |
char currentChar = inputString.charAt(i); | |
switch (currentChar) { | |
case '{': | |
myStack.push('{'); | |
break; | |
case '[': | |
myStack.push('['); | |
break; | |
case '(': | |
myStack.push('('); | |
break; | |
case ')': | |
if (!myStack.empty() && myStack.peek().equals('(')) myStack.pop(); | |
else valid = false; | |
break; | |
case ']': | |
if (!myStack.empty() && myStack.peek().equals('[')) myStack.pop(); | |
else valid = false; | |
break; | |
case '}': | |
if (!myStack.empty() && myStack.peek().equals('{')) myStack.pop(); | |
else valid = false; | |
break; | |
} | |
} | |
if (myStack.empty() && valid) isValid = true; | |
System.out.println("isValid --> " + isValid); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment