문제
표현식에서 괄호를 제거하여 간단한 표현식을 만들어 봅시다.
해결책
예시 1
Input: A string expression with bracket is as follows: (x+y)+(z+q) The output is as follows: x+y+z+q
예시 2
The input is as follows: (x-y+z)-p+q The output is as follows: x-y+z-p+q
알고리즘
주어진 입력에서 대괄호를 제거하는 알고리즘을 참조하십시오.
1단계:런타임에 입력을 선언하고 읽습니다.
2단계:문자열을 탐색합니다.
3단계:입력 문자열의 각 요소를 새 문자열에 복사합니다.
4단계:요소로 괄호가 있는 경우 공백으로 대체합니다.
예시
다음은 주어진 입력에서 대괄호를 제거하는 C 프로그램입니다 -
#include<stdio.h>
int main(){
int i=0,c=0,j=0;
char a[100],b[100];
printf("\nEnter the string :");
scanf("%s",a);
while(a[i]!='\0'){
if((a[i]=='(') && (a[i-1]=='-')){
(c=0)?j=i:j=c;
while(a[i]!=')'){
if(a[i+1]=='+')
b[j++]='-';
else if(a[i+1]=='-')
b[j++]='+';
else if(a[i+1]!=')')
b[j++]=a[i+1];
i++;
}
c=j+1;
}
else if(a[i]=='(' && a[i-1]=='+'){
(c==0)?j=i:j=c;
while(a[i]!=')'){
b[j++]=a[i+1];
i++;
}
j–;
c=j+1;
}
else if(a[i]==')'){
i++;
continue;
} else {
b[j++]=a[i];
}
i++;
}
b[j]='\0';
printf("%s",b);
return 0;
} 출력
위의 프로그램이 실행되면 다음과 같은 출력을 생성합니다 -
Enter the string:(x+y)-z x+y-z