Split Balanced Parentheses
Split Balanced Parentheses
PROBLEM STATEMENT :
The program must accept a string S as the input. The string S contains only parentheses, where each open parenthesis '(' has a matching close parenthesis ')'. The program must split the string S into as many substrings as possible, where the parentheses in each substring must be balanced.
Boundary Condition(s):
2 <= Length of S <= 100
Input Format:
The first line contains S.
Output Format:
The lines contain the substrings of S based on the given conditions.
Example Input/Output 1:
Input: ()
()()
Output:
()
()
Explanation:
Example Input/Output 2:
Input: ()
()((())())((()))(()(())())
Output:
()
((())())
((()))
(()(())())
Example Input/Output 3:
Input: ()
(()(()()))()(((()))()(()))(()((()))(())())(())()
Output:
(()(()()))
()
(((()))()(()))
(()((()))(())())
(())
()
1) LEARN THRICE
👇
2) THINK TWICE
👇
3) APPLY ONCE
SOLUTION :
C (Programming Language)
#include<stdio.h>
#include<stdlib.h>
int main()
{
int i,cnt=0;
char s[101];
scanf("%s",s);
for(i=0;s[i]!='\0';++i) {
if(s[i]=='(') {
cnt++;
}
else {
cnt--;
}
printf("%c",s[i]);
if(cnt==0) {
printf("\n");
}
}
}
C++ (CPP)
#include <bits/stdc++.h>
using namespace std;
int main(int argc, char** argv)
{
int cnt=0,i;
string s,t="";
cin>>s;
for(i=0;i<s.size();++i) {
if(s[i]=='(') cnt++;
else cnt--;
t+=s[i];
if(cnt==0) {
cout<<t<<"\n";
t="";
}
}
}
JAVA
import java.util.*;
public class Hello {
public static void main(String[] args) {
Scanner sc=new Scanner(System.in);
String s=sc.nextLine().trim(),t="";
int i,cnt=0;
for(i=0;i<s.length();++i) {
if(s.charAt(i)=='(') cnt++;
else cnt--;
t+=(s.charAt(i)+"");
if(cnt==0) {
System.out.println(t);
t="";
}
}
}
}
PYTHON
s=input().strip()
l=len(s)
c=0
res=''
for i in range(l):
if s[i]=='(':
c+=1
else:
c-=1
res+=s[i]
if c==0:
print(res)
res=''

Comments
Post a Comment