Thursday, May 28, 2015

L Question: Find depth for (00)

public static int findDepth(String str){
  Stack<Integer> stack = new Stack<Integer>();
  int maxdep = -1;
  stack.push(0);
  for(int i = 0; i < str.length(); i ++){
   char c = str.charAt(i);
   if(stack.isEmpty()) return -1;
   Integer oldcount = stack.pop();
   switch(c){
   case '(':
    if(oldcount >= 2) return -1;
    stack.push(oldcount+1);
    stack.push(0);
    break;
   case '0':
    if(oldcount >= 2) return -1;
    stack.push(oldcount+1);
    break;
   case ')':
    if(oldcount != 2) return -1;
    if(maxdep < stack.size()-1) maxdep = stack.size()-1;
    break;
   default:
    return -1;
   }
  }
  if(stack.size()!=1 || stack.pop()!= 1) return -1;
  else return maxdep;
 }

No comments:

Post a Comment