I am implementing balanced parenthesis problem on hacker rank. link When i run my program on hackerrank ide, it shows following ⚠warning .
Solution.cpp: In function ‘std::__cxx11::string isBalanced(std::__cxx11::string)’:
Solution.cpp:51:17: warning: this ‘if’ clause does not guard... [-Wmisleading-indentation]
if('{'!=s[i])
^~
Solution.cpp:54:21: note: ...this statement, but the latter is misleadingly indented as if it were guarded by the ‘if’
bracket.pop();
^~~~~~~
Solution.cpp:25:16: error: control reaches end of non-void function [-Werror=return-type]
stack<char>bracket;
^~~~~~~
cc1plus: some warnings being treated as errors
When i run my program in local computer, then my program crashes after reading a integer (test case)
.
For ease of code i added comment to it.
The problem is showing in isBalanced()
function.
My Code:
#include <bits/stdc++.h>
using namespace std;
// return true if the passed character belongs to ar[], false otherwise
bool find(char ch,char ar[]){
for(int i=0;i<3;i++)
if(ar[i]==ch)
return true;
return false;
}
string isBalanced(string s) {
int size=s.length();
stack<char>bracket;
char open[3]={'{','[','('};
// if size of string is odd then expression is not balanced
if(size%2!=0)
return "NO";
for(int i=0;i<size;i++){
// if current bracket is opening bracket
// then push it into bracket stack
if(find(s[i],open)){
bracket.push(s[i]);
}
// if current bracket is closing bracket
// then match top element of bracket stack with current bracket
// if both are matched then pop an element from bracket stack
// if both are not matched return "NO"
else{
// if there is an element to match and current stack is empty then expression is not balanced
if(bracket.empty())
return "NO";
else
switch (bracket.top()) {
case '{':
if('{'!=s[i])
return "NO";
bracket.pop();
break;
case '(':
if('('!=s[i])
return "NO";
bracket.pop();
break;
case '[':
if('['!=s[i])
return "NO";
bracket.pop();
break;
}
bracket.pop();
}
return "YES";
}
}
int main()
{
int t;
cin >> t;
for (int t_itr = 0; t_itr < t; t_itr++) {
string s;
getline(cin, s);
string result = isBalanced(s);
cout << result << "\n";
}
return 0;
}