Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
91 changes: 91 additions & 0 deletions Yash2110-Yash/BalancedBrackets(HR)/BalancedBrackets.cpp
Original file line number Diff line number Diff line change
@@ -0,0 +1,91 @@
#include <bits/stdc++.h>

using namespace std;

string ltrim(const string &);
string rtrim(const string &);

/*
* Complete the 'isBalanced' function below.
*
* The function is expected to return a STRING.
* The function accepts STRING s as parameter.
*/

string isBalanced(string s)
{
stack<char> st;
int len = s.size();
int i;

for(i=0;i<len;i++)

{
if(s[i] == '(' || s[i] == '{' || s[i] == '[')
{
st.push(s[i]);
}

else if( !st.empty() &&
(s[i] == ')' && st.top() == '(' ||
s[i] == '}' && st.top() == '{' ||
s[i] == ']' && st.top() == '[')) {
st.pop();
}

else
return "NO";

}

if(st.empty())
return "YES";
else
return "NO";

}

int main()
{
ofstream fout(getenv("OUTPUT_PATH"));

string t_temp;
getline(cin, t_temp);

int t = stoi(ltrim(rtrim(t_temp)));

for (int t_itr = 0; t_itr < t; t_itr++) {
string s;
getline(cin, s);

string result = isBalanced(s);

fout << result << "\n";
}

fout.close();

return 0;
}

string ltrim(const string &str) {
string s(str);

s.erase(
s.begin(),
find_if(s.begin(), s.end(), not1(ptr_fun<int, int>(isspace)))
);

return s;
}

string rtrim(const string &str) {
string s(str);

s.erase(
find_if(s.rbegin(), s.rend(), not1(ptr_fun<int, int>(isspace))).base(),
s.end()
);

return s;
}
11 changes: 11 additions & 0 deletions Yash2110-Yash/BalancedBrackets(HR)/README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,11 @@
Question:
</br>
Link: https://www.hackerrank.com/challenges/balanced-brackets/problem?h_r=internal-search
</br>
Answer:
</br>
- Here we use stacks to first store the opening brackets and then compare the last added bracket with the closing brakcets being added.
</br>
- We keep poping out the brackets from the stack which are balanced i,e they find their opposite pair in sequence
</br>
- If in the end we are able to make the stack empty then the string has balanced brackets