Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Create asteroid_collision.cpp #593

Open
wants to merge 3 commits into
base: main
Choose a base branch
from
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
25 changes: 25 additions & 0 deletions asteroid_collision.cpp
Original file line number Diff line number Diff line change
@@ -0,0 +1,25 @@
class Solution {
public:
vector<int> asteroidCollision(vector<int>& asteroids) {
vector<int> ans;
int n=asteroids.size();
for(int i=0;i<n;i++){
int curr=asteroids[i];
if(ans.empty() || curr>0 ){
ans.push_back(curr);
}
else{
while(!ans.empty() && ans.back()>0 && ans.back()<abs(curr)){
ans.pop_back();
}
if(!ans.empty() && ans.back()+curr==0){
ans.pop_back();
}
else if(ans.empty() || ans.back()<0){
ans.push_back(curr);
}
}
}
return ans;
}
};
68 changes: 68 additions & 0 deletions balanced_parenthesis.cpp
Original file line number Diff line number Diff line change
@@ -0,0 +1,68 @@
#include<bits/stdc++.h>
using namespace std;

bool isValid(string s)
{
int n = s.size();
stack<char> st;
bool ans = true;
for (int i = 0; i < n; i++)
{
if (s[i] == '{' or s[i] == '(' or s[i] == '[')
{
st.push(s[i]);
}
else if (s[i] == ')')
{
if (!st.empty() and st.top() == '(')
{
st.pop();
}
else
{
ans = false;
break;
}
}
else if (s[i] == ']')
{
if (!st.empty() and st.top() == '[')
{
st.pop();
}
else
{
ans = false;
break;
}
}
else if (s[i] == '}')
{
if (!st.empty() and st.top() == '{')
{
st.pop();
}
else
{
ans = false;
break;
}
}
}
if(!st.empty()){
return false;
}
return ans;
}
int main()
{
string s = "{([])}";

if(isValid(s)){
cout<<"valid string ";
}
else{
cout<<"invalid string ";
}
return 0;
}