Thursday, May 28, 2015

L Question: nested HashMap

http://stackoverflow.com/questions/12143500/iterate-over-nested-multi-dimensional-hashmap

L Question: Insert a Node in a BST

public class Tree {

    private Node root=null;

    public Node getRoot() {
        return root;
    }

    public void insertData(int data)
    {
        Node node=new Node(data,null,null);
        insert(node,this.root);

    }

    private Node insert(Comparable<Node> node,Node root1)
    {
            if(root1==null)
            {

                root1=new Node(((Node)node).getData(),null,null);
                if(this.root==null)
                {
                    this.root=root1;
                }
            }
            else if(node.compareTo(root1) <0)
            {
                root1.setLeftChild(insert(node,root1.getLeftChild()));
            }
            else if(node.compareTo(root1) >0)
            {

                root1.setLeftChild(insert(node,root1.getRightChild()));
            }

     return root1;  
    }
}

L Question: is Number

public static boolean isNumber(String str) {
  int n = str.length();
  boolean hexFound = false;
  boolean decimalFound = false;
  boolean numFound = false;
  boolean signFound = false;
  boolean zeroFound = false;
  for(int i = 0; i < n ; i++) {
   char ch = str.charAt(i);
   switch(ch) {
    case '-':
    case '+':
     if(signFound || i != 0) {
      return false;
     } else {
      signFound = true;
     }
    break;
    
    case '.':
     if(hexFound || decimalFound || i == n-1) {
      return false;
     } else {
      decimalFound = true;
     }
    break;
    
    case 'x': 
     if(!zeroFound || hexFound || numFound || signFound) {
      return false;
     } else {
      hexFound = true;
     }
    break;
    
    case '0':
     zeroFound = true;
    break;
    
    default:
     if(ch >= 'a' && ch <='f') {
      if(!hexFound) {
       return false;
      }
     } else if(ch >= '0' && ch <= '9') {
      numFound = true;
     } else {
      return false;
     }
   }
  }
  return true;
 }

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;
 }