Amazon Interview Question
InternsCountry: India
Interview Type: Written Test
Use stack :
public static bool IsBalanced(string s)
{
Stack<char> s = new Stack<char>();
foreach(var ch in s)
{
if (ch == '(' || ch == '[' || ch == '{') s.Push(ch);
else
{
if (stack.Count == 0) return false;
int top = s.Pop();
if ((ch == ')' && top != '(') ||
(ch == ']' && top != '[') ||
(ch == '}' && top != '{')) return false;
}
}
return s.Count == 0;
}
//Author : A.Nasimunni
#include<stdio.h>
#include<stdlib.h>
#include<string.h>
main()
{
char a[100];printf("\n\n\t\t Enter your string : ");
gets(a);
int k=strlen(a);int i,p1=0,p2=0,c1=0,c2=0,s1=0,s2=0;
for(i=0;i<k;i++)
{
if(a[i]=='('){p1=p1+1;}else if(a[i]==')'){p2=p2+1;}
else if(a[i]=='['){s1=s1+1;}else if(a[i]==']'){s2=s2+1;}
else if(a[i]=='{'){c1=c1+1;}else if(a[i]=='}'){c2=c2+1;}
else {p1=p1;s2=s2;}
}
if (p1==p2 && c1==c2 && s1==s2)
{
printf("\n\t\tTrue\n\n");
}
else
{
printf("\n\t\tFlase\n\n");
}
}
//// parenthesis cheaking........
- pintuguptajuit(PINTU GUPTA) March 23, 2013void check(char *a)
{
struct s
{
char ch;
s*next;
};
s *st=NULL;
s*node=NULL;
if(a=='\0')
{
cout<<"TRUE";
return ;
}
else
{
while(a[0]!='\0')
{
{
node=(s*)malloc(sizeof(s));
char c=a[0];
switch(c)
{
case '[':
if(st==NULL)
{
node->ch=c;
node->next=NULL;
st=node;
a++;
}
else
{
if(st->ch=='('||st->ch=='{')
{
cout<<"FALSE";
return ;
}
else
{
node->ch=c;
node->next=st;
st=node;
a++;
}
}
break;
case '{':
if(st==NULL)
{
node->ch=c;
node->next=NULL;
st=node;
a++;
}
else
{
if(st->ch=='(')
{
cout<<"FALSE";
return ;
}
else
{
node->ch=c;
node->next=st;
st=node;
a++;
}
}
break;
case '(':
if(st==NULL)
{
node->ch=c;
node->next=NULL;
st=node;
a++;
}
else
{
node->ch=c;
node->next=st;
st=node;
a++;
}
break;
case ')':
if(st==NULL||st->ch=='{'||st->ch=='[')
{
cout<<"FALSE";
return ;
}
else
{
if(st->ch=='(')
{
s *newnode=st;
st=st->next;
free(newnode);
a++;
}
}
break;
case '}':
if(st==NULL||st->ch=='('||st->ch=='[')
{
cout<<"FALSE";
return ;
}
else
{
if(st->ch=='{')
{
s *newnode=st;
st=st->next;
free(newnode);
a++;
}
}
break;
case ']':
if(st==NULL||st->ch=='{'||st->ch=='(')
{
cout<<"FALSE";
return ;
}
else
{
if(st->ch=='[')
{
s *newnode=st;
st=st->next;
free(newnode);
a++;
}
}
break;
default :
a++;
if(a[0]=='\0')
{
cout<<"TRUE";
return ;
}
break;
}
}
}
if(st==NULL&&a[0]=='\0')
{
cout<<"TRUE";
return ;
}
if(st!=NULL)
{
cout<<"\nFALSE";
return ;
}
}
}