4
The task:
Pedrinho and Zezinho need to study solving mathematical expressions for a test they will do. For this, they want to solve many exercises before the test. As they know how to program, so they decided to make a generator of mathematical expressions.
The expression generator they created works in two phases.
In the first phase a string containing only the characters is generated '{', '[', '(', '}', ']' e ')'
.
In the second phase, the generator adds the numbers and operators in the structure created in the first phase. A character string is said to be well defined (or valid) if it meets the following properties:
- It is an empty string (contains no character).
- It consists of a well-defined chain wrapped in parentheses, brackets or keys. Therefore, if the string S is well defined, then the strings (S), [S] and {S} are also well defined.
- It is formed by concatenating two well-defined strings. Therefore, if the strings X and Y are well-defined, the string XY is well-defined.
After Pedrinho and Zezinho generated some mathematical expressions, they realized that there was some error in the first phase of the generator. Some chains were not well defined. They want to start solving the expressions as soon as possible, and knowing that you are a great programmer (and participate in OBI) have decided to ask you to write a program that given several generated strings in the first phase, determine which ones are well defined and which ones are not.
Input example:
12
()
[]
{}
(]
}{
([{}])
{}()[]
()]
{[]
(
(([{}{}()[]])(){}){}
(((((((((({([])}])))))))))
Respective exit:
S
S
S
N
N
S
S
N
N
N
S
N
The code I tried to implement:
#include<stdio.h>
#include<string.h>
int main () {
int N, i, res[10000]={0}, vetor[6]={0}, j;
char exp[100000][30], *p;
scanf ("%d", &N);
for (i=0;i<N;i++){
scanf("%s", exp[i]);
p=exp[i];
for(j=0;j<sizeof(exp); j++){
if (*p=='{')vetor[0]++;
else if (*p=='[')vetor[1]++;
else if (*p=='(')vetor[2]++;
else if (*p==')' && vetor[2]>vetor[3])vetor[3]++;
else if (*p==']' && vetor[1]>vetor[4])vetor[4]++;
else if (*p=='}' && vetor[0]>vetor[5])vetor[5]++;
if (vetor[0]==vetor[5] && vetor[1]==vetor[4] && vetor[2]==vetor[3]) res[i]=1;
else res[i]=0;
p++;
}
}
for (i=0;i<N;i++){
if (res[i]) printf("S\n");
else printf("N\n");
}
return 0;
}
I’m learning to use strings and pointers. With this code, the answer of the output is always N and I’m not identifying why, will anyone help me to solve this problem?
Simply delete the other answer if you want to keep only one answer. You can also join both in one.
– user28595