Thursday, 11 February 2016

Find the depth of letters in a string

A string is given which has letters from English alphabet and parentheses. The depth of a letter is defined as the number of balanced parentheses it is surrounded by. Write a  C program to find the depth of each letter in the input string.

Explanation:

(a(b)((cd)e)f)g

g is at depth 0
a and f are at depth 1
b and e are at depth 2
c and d are at depth 3

Solution:

#include<stdio.h>
#include<string.h>
int main()
 {
  int a=0,i,set=0;
  char input[100];
  scanf("%s",input);
  for(i=0;input[i]!='\0';i++)
   {
    switch(input[i])
     {
        case '(':
                a++;
                break;
        case ')':
                a--;
                break;
        default :  
                printf("%d ",a);
                set = 1;
      }   
      
   }
  if(set==0)
     printf(" #");
  else
     printf("#");
  return 0;

}

No comments:

Post a Comment