0
Sponsored Links


Ad by Google
This types of questions are always on demand like java program to find missing number from an array, specially in product based companies. Interviews are totally different between product based company and service based company.
In product based company interviewer want to evaluate not only technical part, but also they want to evaluate your logical analysis power, by asking different puzzles or logical problems.
In our previous post we have seen 10 basic core java interview questions here. And in this post we will show you a very simple program to balanced the parenthesis, of course there are lot of ways to solve this and we are using one of the popular data structure Last-In-First-Out(LIFO) STACK implementation.
The performance of the program is in o(n).

BalanceParenthesis.java

package com.javamakeuse.poc;

import java.util.Stack;

public class BalanceParenthesis {
 public static void main(String[] args) {
  System.out.println(isParenthesisBalanced("()"));
  System.out.println(isParenthesisBalanced("{+1(23+34)}"));
  System.out.println(isParenthesisBalanced("{()}"));
  System.out.println(isParenthesisBalanced("{(()}"));
 }

 public static boolean isParenthesisBalanced(String value) {
  Stack<Character> charStack = new Stack<>();
  for (Character ch : value.toCharArray()) {
   if (ch == '(' || ch == '{' || ch == '[') {
    charStack.push(ch);
   } else if (ch == '}') {
    if (charStack.isEmpty() || charStack.peek() != '{') {
     return false;
    } else {
     charStack.pop();
    }
   } else if (ch == ')') {
    if (charStack.isEmpty() || charStack.peek() != '(') {
     return false;
    } else {
     charStack.pop();
    }
   } else if (ch == ']') {
    if (charStack.isEmpty() || charStack.peek() != '[') {
     return false;
    } else {
     charStack.pop();
    }
   }
  }
  return charStack.isEmpty();
 }

}

OUTPUT:
true
true
true
false

Sponsored Links

0 comments:

Post a Comment