Sunday 15 March 2015

Nagarro: check whether combination of paranthis is valid or not?






package parenthesis;

import java.util.Scanner;


public class CheckParenthesis2 {
 static int max = 23434;
 static char stack[] = new char[max];
 static int top = -1;
 static char symbol[] = { '(', ')', '{', '}', '[', ']' };

 public static void main(String str[]) {
  Scanner sc = new Scanner(System.in);
  String input = sc.nextLine().trim();
  System.out.println("Input String is " + input);

  System.out.println(check(input));

 }

 static boolean check(String str) {
  int s_index = 0;
  int e_index = str.length() - 1;
  char ch = 0, temp = 0;
  int s = 0;
  boolean flag = false;
  while (s_index <= e_index) {
   flag = true;

   ch = str.charAt(s_index++);
   if (ch == symbol[0] || ch == symbol[2] || ch == symbol[4]) {
    flag = false;
    push(ch);
   } else if (ch == symbol[s = 1] || ch == symbol[s = 3]
     || ch == symbol[s = 5]) {
    temp = pop();
    if (temp == symbol[s - 1])
     continue;
    else {
     flag = false;
     break;
    }

   }

  }
  return flag;
 }

 static void push(char ch) {
  stack[++top] = ch;
 }

 static char pop() {
  return stack[top--];
 }

}