Parenthesis Checker Geeks For Geeks Total Time Complexity O(String length) Space O(1) constant
Solution 1: Brute Force
(Accuracy: 100% , Time 0.5/1.6 )
static boolean ispar(String str)
{
int c1=0;
int c2=0;
int c3=0;
int c4=0;
int c5=0;
int c6=0;
int c7=0;
if((str.length()/2)*2==str.length()){//Checking weather string length is even or not
//System.out.println("Confirmation that this string length is even..............");
for(int i=0;i<str.length();i++){
if(str.charAt(i)=='{'){
c1++;
}
else if(str.charAt(i)=='}'){
c2++;
}
else if(str.charAt(i)=='['){
c3++;
}
else if(str.charAt(i)==']'){
c4++;
}
else if(str.charAt(i)=='('){
c5++;
}
else if(str.charAt(i)==')'){
c6++;
}
else{
c7++;
break;
}
}
if((c1==c2) && (c3==c4) && (c5==c6)){
//System.out.println("Confirmed that for each charater there is a close brackett. ");
return true;
}
else if(c7>0){
//System.out.println("No");
return false;
}
else{
//System.out.println("No");
return false;
}
}
else{
//System.out.println("No");
return false;
}
=======================================================================
Solution 2: Using Stacks
(Accuracy: 100% , Total Time 0.6/1.6)
Stack<Character> stack=new Stack<Character>();
for(int i=0;i<str.length();i++){
if(stack.isEmpty()){
stack.push(str.charAt(i));
}
else if(stack.peek()=='{' && str.charAt(i)=='}'){
stack.pop();
}
else if(stack.peek()=='[' && str.charAt(i)==']'){
stack.pop();
}
else if(stack.peek()=='(' && str.charAt(i)==')'){
stack.pop();
}
else{
stack.push(str.charAt(i));
}
}
if(stack.isEmpty()){
return true;
}
else{
return false;
}
=========================================================================
Thanks for reading.
Hope it helped you 😊.
Comments
Post a Comment