Last active
June 5, 2018 09:21
-
-
Save ariyike/a9e4ae5fe04e3163b67c8b4698214c1c to your computer and use it in GitHub Desktop.
This is a stack implementation problem which checks that with any given String from input and checks it for brackets and verifies that each bracket is closed(Hence the balance)
This file contains 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 pkgclass.projects; | |
import java.util.HashMap; | |
import java.util.Objects; | |
import java.util.Stack; | |
/** | |
* | |
* @author Morema and Ariyike | |
*/ | |
public class IsBalanced { | |
Stack<Character> stack; | |
public IsBalanced() { | |
this.stack = new Stack<>(); | |
} | |
public boolean checkBalance(String input){ | |
HashMap <Character, Character> brackets = new HashMap<>(); | |
brackets.put(')','('); | |
brackets.put('}','{'); | |
brackets.put(']','['); | |
int count; | |
for (count=0;count<input.length();count++){ | |
Character checkThis = input.charAt(count); | |
if (checkThis == '(' || checkThis == '[' || checkThis == '{'){ | |
stack.push(checkThis); | |
} | |
else if (checkThis == ')' || checkThis == ']' || checkThis == '}'){ | |
if (stack.empty()){ | |
return false; | |
} | |
else if (Objects.equals(brackets.get(checkThis), stack.peek())){ | |
stack.pop(); | |
} | |
else{ | |
return false; | |
//stack.push(checkThis); | |
} | |
} | |
//stack.push(); | |
} | |
return stack.empty() != false; | |
} | |
public static void main (String [] args){ | |
IsBalanced papa = new IsBalanced(); | |
Scanner in = new Scanner(System.in); | |
String input = in.next(); | |
System.out.println(papa.checkBalance(input)); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment