I am trying to create a program that takes a string as an argument into its constructor. I need a method that checks whether the string is a balanced parenthesized expressio
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.Scanner;
import java.util.Stack;
public class BalancedParenthesisWithStack {
/*This is purely Java Stack based solutions without using additonal
data structure like array/Map */
public static void main(String[] args) throws IOException {
Scanner sc = new Scanner(System.in);
/*Take list of String inputs (parenthesis expressions both valid and
invalid from console*/
List<String> inputs=new ArrayList<>();
while (sc.hasNext()) {
String input=sc.next();
inputs.add(input);
}
//For every input in above list display whether it is valid or
//invalid parenthesis expression
for(String input:inputs){
System.out.println("\nisBalancedParenthesis:"+isBalancedParenthesis
(input));
}
}
//This method identifies whether expression is valid parenthesis or not
public static boolean isBalancedParenthesis(String expression){
//sequence of opening parenthesis according to its precedence
//i.e. '[' has higher precedence than '{' or '('
String openingParenthesis="[{(";
//sequence of closing parenthesis according to its precedence
String closingParenthesis=")}]";
//Stack will be pushed on opening parenthesis and popped on closing.
Stack<Character> parenthesisStack=new Stack<>();
/*For expression to be valid :
CHECK :
1. it must start with opening parenthesis [()...
2. precedence of parenthesis should be proper (eg. "{[" invalid
"[{(" valid )
3. matching pair if( '(' => ')') i.e. [{()}(())] ->valid [{)]not
*/
if(closingParenthesis.contains
(((Character)expression.charAt(0)).toString())){
return false;
}else{
for(int i=0;i<expression.length();i++){
char ch= (Character)expression.charAt(i);
//if parenthesis is opening(ie any of '[','{','(') push on stack
if(openingParenthesis.contains(ch.toString())){
parenthesisStack.push(ch);
}else if(closingParenthesis.contains(ch.toString())){
//if parenthesis is closing (ie any of ']','}',')') pop stack
//depending upon check-3
if(parenthesisStack.peek()=='(' && (ch==')') ||
parenthesisStack.peek()=='{' && (ch=='}') ||
parenthesisStack.peek()=='[' && (ch==']')
){
parenthesisStack.pop();
}
}
}
return (parenthesisStack.isEmpty())? true : false;
}
}
The improved method, from @Smartoop.
public boolean balancedParenthensies(String str) {
List<Character> leftKeys = Arrays.asList('{', '(', '<', '[');
List<Character> rightKeys = Arrays.asList('}', ')', '>', ']');
Stack<Character> stack = new Stack<>();
for (int i = 0; i < str.length(); i++) {
char c = str.charAt(i);
if (leftKeys.contains(c)) {
stack.push(c);
} else if (rightKeys.contains(c)) {
int index = rightKeys.indexOf(c);
if (stack.isEmpty() || stack.pop() != leftKeys.get(index)) {
return false;
}
}
}
return stack.isEmpty();
}
This is my own implementation. I tried to make it the shortest an clearest way possible:
public static boolean isBraceBalanced(String braces) {
Stack<Character> stack = new Stack<Character>();
for(char c : braces.toCharArray()) {
if(c == '(' || c == '[' || c == '{') {
stack.push(c);
} else if((c == ')' && (stack.isEmpty() || stack.pop() != '(')) ||
(c == ']' && (stack.isEmpty() || stack.pop() != '[')) ||
(c == '}' && (stack.isEmpty() || stack.pop() != '{'))) {
return false;
}
}
return stack.isEmpty();
}
This is my implementation for this question. This program allows numbers, alphabets and special characters with input string but simply ignore them while processing the string.
CODE:
import java.util.Scanner;
import java.util.Stack;
public class StringCheck {
public static void main(String[] args) {
boolean flag =false;
Stack<Character> input = new Stack<Character>();
System.out.println("Enter your String to check:");
Scanner scanner = new Scanner(System.in);
String sinput = scanner.nextLine();
char[] c = new char[15];
c = sinput.toCharArray();
for (int i = 0; i < c.length; i++) {
if (c[i] == '{' || c[i] == '(' || c[i] == '[')
input.push(c[i]);
else if (c[i] == ']') {
if (input.pop() == '[') {
flag = true;
continue;
} else {
flag = false;
break;
}
} else if (c[i] == ')') {
if (input.pop() == '(') {
flag = true;
continue;
} else {
flag = false;
break;
}
} else if (c[i] == '}') {
if (input.pop() == '{') {
flag = true;
continue;
} else {
flag = false;
break;
}
}
}
if (flag == true)
System.out.println("Valid String");
else
System.out.println("Invalid String");
scanner.close();
}
}
public static boolean isBalanced(String expression) {
if ((expression.length() % 2) == 1) return false;
else {
Stack<Character> s = new Stack<>();
for (char bracket : expression.toCharArray())
switch (bracket) {
case '{': s.push('}'); break;
case '(': s.push(')'); break;
case '[': s.push(']'); break;
default :
if (s.isEmpty() || bracket != s.peek()) { return false;}
s.pop();
}
return s.isEmpty();
}
}
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
String expression = in.nextLine();
boolean answer = isBalanced(expression);
if (answer) { System.out.println("YES");}
else { System.out.println("NO");}
}
Here is the Code. I have tested all the possible test case on Hacker Rank.
static String isBalanced(String input) {
Stack<Character> stack = new Stack<Character>();
for (int i = 0; i < input.length(); i++) {
Character ch = input.charAt(i);
if (input.charAt(i) == '{' || input.charAt(i) == '['
|| input.charAt(i) == '(') {
stack.push(input.charAt(i));
} else {
if (stack.isEmpty()
|| (stack.peek() == '[' && ch != ']')
|| (stack.peek() == '{' && ch != '}')
|| (stack.peek() == '(' && ch != ')')) {
return "NO";
} else {
stack.pop();
}
}
}
if (stack.empty())
return "YES";
return "NO";
}