If we have an expression in which only parenthesis '( )' is used and wanted to check that it has matching pairs, we can use this simple Technic to find out whether the expression is correct or not.
Limitations:
Algorithm for parenthesis matching without using stack:
In this algorithm, we will use COUNTER to count the difference of count of opening and closing parenthesis. The step are as follows:- Set COUNTER = 0 and VALID = true
- Get the input string
- While the end of string
- If the current character is left parenthesis
- Increment counter i.e. ++COUNTER
- If the current character is right parenthesis
- Decrement counter i.e. - -COUNTER
- If at any step closing parenthesis occur having no opening parenthesis i.e. COUNTER < 0
- VALID = false
- If the current character is left parenthesis
- Return COUNTER == 0 && VALID
- Can check only one type of bracket
Function to check matching parenthesis without using stack:
int check_parenthesis(char *str){
int counter = 0, i = -1, valid = 1;
while(str[++i]){
if(str[i] == ' ')
continue;
if(str[i] == '(')
counter++;
if(str[i] == ')')
counter--;
if(counter < 0){
valid = 0;
}
}
return valid && counter == 0;
}
Program to check matching parenthesis without using stack:
#include <stdio.h>
int check_parenthesis(char *str){
int counter = 0, i = -1, valid = 1;
while(str[++i]){
if(str[i] == ' ')
continue;
if(str[i] == '(')
counter++;
if(str[i] == ')')
counter--;
if(counter < 0){
valid = 0;
}
}
return valid && counter == 0;
}
int main(){
char *str = "()(()())";
if(check_parenthesis(str)){
printf("String %s has matching parenthesis\n", str);
}
else{
printf("String %s hasn't matching parenthesis\n", str);
}
}
String (A+B)*((C/D)-(E*F)) has matching parenthesis
Comments
Post a Comment