Sunday, September 28, 2014

Java Program to Check whether a Expression is Valid


Java Program to Check whether a Expression is Valid
// Using count variables for character and brackets

 public static boolean isValidStr(String str)
 {
  int count = 0, brackets = 0;
  for(int i = 0; i< str.length(); i++)
  {
   char ch = str.charAt(i);
   
   switch(ch)
   {
    case '+':
     count--; 
     break;
    case '-':
     count--; 
     break;
    case '*':
     count--; 
     break;
    case '/':
     count--; 
     break;
    case '(':
     brackets++; 
     break;
    case ')':
     brackets--; 
     break;
    default:
     count++; 
     break;
   }
   
   if(count > 1 || count < 0 || brackets < 0) return false;
   
  }
  
  if(brackets != 0) return false;
  
  if(count != 1) return false;
  
  return true;
  
 }