I was solving the balanced parentheses problem using stack implementation when I came across this situation wherein I was using the 'else-if' statements to check for the closing braces but this gave a different output than the expected one. On changing all the 'else-if' statements to plain 'if' statements the code worked just fine. I want to know why this happened because I always thought that using 'else-if' statements was a better practice.
int main(){
stack<char> bracks;
string s; // input string: {a+(b+c-[e-f])*d}
cin >> s;
for(int i = 0; i < s.size(); i++){
if(s[i] == '{' || s[i] == '(' || s[i] == '[') bracks.push(s[i]);
else if(s[i] == '}')
if(bracks.top() == '{') bracks.pop();
else if(s[i] == ')')
if(bracks.top() == '(') bracks.pop();
else if(s[i] == ']')
if(bracks.top() == '[') bracks.pop();
}
if(bracks.empty()) cout << "Balanced\n";
else cout << "Unbalanced\n";
}
Expected output for the input string : "{a+(b+c-[e-f])*d}" is "Balanced" but I'm getting "Unbalanced" as the output.
Aucun commentaire:
Enregistrer un commentaire